国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數(shù)據(jù)庫 > SQL Server > 正文

使用c#構(gòu)造date數(shù)據(jù)類型

2024-08-31 01:01:22
字體:
供稿:網(wǎng)友
/***********************************
作者:trieagle(讓你望見影子的墻)
日期:2009.8.14
注: 轉(zhuǎn)載請(qǐng)保留此信息
************************************/
使用c#構(gòu)造date數(shù)據(jù)類型
在sql server2005沒有實(shí)現(xiàn)date類型,但是提供了很好的擴(kuò)展性,可以利用CLR來構(gòu)造date類型。有一部分是參考了Fc的代碼寫的。
步驟:
1、在vs 2005中新建項(xiàng)目,一次選擇c#——>>數(shù)據(jù)庫——>>sql server項(xiàng)目,輸入項(xiàng)目名稱
2、選擇要連接的數(shù)據(jù)庫
3、在項(xiàng)目名稱右鍵,添加——>>新建項(xiàng)——>>用戶定義的類型——>>輸入類型名稱
4、代碼如下:

復(fù)制代碼 代碼如下:


using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedTypeFormat.UserDefined ,IsByteOrdered=true,MaxByteSize =20,ValidationMethodName="ValidateDate")]
public struct date : INullable,IBinarySerialize
{
// 私有成員
private bool m_Null;
private string m_date;
public override string ToString()
{
if (this.m_Null)
return "null";
else
{
return this.m_date;
}
}
public bool IsNull
{
get
{
return m_Null;
}
}
public static date Null
{
get
{
date h = new date();
h.m_Null = true;
return h;
}
}
public static date Parse(SqlString s)
{
if (s.IsNull || (!s.IsNull && s.Value.Equals("")))
return Null;
else
{
date u = new date();
string[] xy = s.Value.Split(" ".ToCharArray());
u.m_date = xy[0];
if (!u.ValidateDate())
throw new ArgumentException ("無效的時(shí)間");
return u;
}
}
public string _date
{
get
{
return this.m_date;
}
set
{
m_Null = true;
m_date = value;
if (!ValidateDate())
throw new ArgumentException("無效的時(shí)間");
}
}
public void Write(System.IO.BinaryWriter w)
{
byte header = (byte)(this.IsNull ? 1 : 0);
w.Write(header);
if (header == 1)
{
return;
}
w.Write(this.m_date);
}
public void Read(System.IO.BinaryReader r)
{
byte header = r.ReadByte();
if (header == 1)
{
this.m_Null = true;
return;
}
this.m_Null = false ;
this.m_date = r.ReadString();
}
private bool ValidateDate() //判斷時(shí)間是否有效
{
try
{
DateTime dt = Convert.ToDateTime(m_date);
return true;
}
catch
{
return false;
}
}
}


5、按F5進(jìn)行部署
6、測(cè)試:

復(fù)制代碼 代碼如下:


CREATE TABLE tb(id int,dt dbo.Date DEFAULT CONVERT(dbo.Date,CONVERT(VARCHAR(10),GETDATE(),120)));
insert into tb(id) values(1)
SELECT id,dt=dt.ToString() FROM tb;
/*
結(jié)果:
id dt
1 2009-08-14
*/
DROP TABLE tb;


注:
1、 如果要對(duì)date類型進(jìn)行日期的加減,可以調(diào)用ToString()方法輸出為字符串,然后轉(zhuǎn)化為datetime類型,然后再進(jìn)行日期的計(jì)算。
2、 不能直接使用select * from tb 來輸出dt列的值,這樣輸出的是一串二進(jìn)制數(shù)
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 黄梅县| 岑溪市| 盈江县| 资溪县| 莆田市| 南京市| 阿尔山市| 景德镇市| 西吉县| 千阳县| 巴彦淖尔市| 新竹县| 鸡西市| 武夷山市| 和政县| 阜康市| 阿鲁科尔沁旗| 潮州市| 巫山县| 金川县| 长寿区| 澄江县| 濮阳市| 邹城市| 株洲县| 永康市| 乌什县| 马尔康县| 定襄县| 沧源| 杭锦后旗| 新营市| 文安县| 中山市| 铜川市| 游戏| 三河市| 阿图什市| 布拖县| 金坛市| 额敏县|