使用c#構造date資料類型

來源:互聯網
上載者:User

/***********************************
作者:trieagle(讓你望見影子的牆)
日期:2009.8.14
註: 轉載請保留此資訊
************************************/
使用c#構造date資料類型
在sql server2005沒有實現date類型,但是提供了很好的擴充性,可以利用CLR來構造date類型。有一部分是參考了Fc的代碼寫的。
步驟:
1、在vs 2005中建立項目,一次選擇c#——>>資料庫——>>sql server項目,輸入項目名稱
2、選擇要串連的資料庫
3、在項目名稱右鍵,添加——>>建立項——>>使用者定義的類型——>>輸入類型名稱
4、代碼如下: 複製代碼 代碼如下: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 ("無效的時間");
return u;
}
}
public string _date
{
get
{
return this.m_date;
}
set
{
m_Null = true;
m_date = value;
if (!ValidateDate())
throw new ArgumentException("無效的時間");
}
}
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() //判斷時間是否有效
{
try
{
DateTime dt = Convert.ToDateTime(m_date);
return true;
}
catch
{
return false;
}
}
}

5、按F5進行部署
6、測試: 複製代碼 代碼如下: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;
/*
結果:
id dt
1 2009-08-14
*/
DROP TABLE tb;

註:
1、 如果要對date類型進行日期的加減,可以調用ToString()方法輸出為字串,然後轉化為datetime類型,然後再進行日期的計算。
2、 不能直接使用select * from tb 來輸出dt列的值,這樣輸出的是一串位元

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.