2012-11-05 60 views
2

設置在創建表我要使用的數據類型SET,但它看起來像有在SQL Server中沒有數據類型SET。我正在尋找微軟的網站,那些是它支持的數據類型:http://msdn.microsoft.com/en-us/library/ms187752.aspxSET數據類型在SQL Server

我應該用哪一個來取代SET

我在MySQL數據庫中使用SET這樣的:

CREATE TABLE IF NOT EXISTS `configurations` (
`index` int(11) NOT NULL AUTO_INCREMENT, 
`user_id` int(11) NOT NULL, 
`configDuration` int(5) NOT NULL, 
`configDurationPerspective` set('list_this_day','list_remaining') NOT NULL, 
PRIMARY KEY (`index`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

,然後當我將數據插入到表中,它看起來是這樣的:

INSERT INTO 'configurations' (index, user_id, configDuration, configDurationPerspective) VALUES (1, 1, 2, 'list_this_day'); 

沒關係的報價。粘貼代碼時出現混亂。

現在我想要做同樣的事情,但在SQL Server中。

+0

你想用SET做什麼?如果你回答,我們可能會提出一種替代方法來做你想做的事情...... – mortb

+0

啊,這裏是定義:http://dev.mysql.com/doc/refman/5.0/en/ set.html。 – mortb

+0

我已編輯我的帖子。是的,確切地說,這是SET的定義。但我想這是針對MySQL的。對於MS SQL,我找不到這樣的東西。 – Apostrofix

回答

2

你會要麼必須使用單獨的位字段(每個價值位數據類型的一列),或者你會包裝值到一個整數數據類型的列。如果您使用整數,您必須使用t-sql bitwise operators來讀取和寫入值。

如果你使用按位運算符,你只會得到一個列 在CREATE TABLE語句應該是這樣的:

CREATE TABLE configurations(
[index] int NOT NULL IDENTITY (1,1) PRIMARY KEY, 
user_id int NOT NULL, 
configDuration int NOT NULL, 
configDurationPerspective int NOT NULL, 
) 

然後你不得不插入有可能像位掩碼值爲1, 2,4,8,16,32到configDurationPerspective

INSERT INTO 'configurations' (index, user_id, configDuration, configDurationPerspective) VALUES (1, 1, 2, 'list_this_day'); 

將轉化

INSERT INTO 'configurations' (index, user_id, configDuration, configDurationPerspective) VALUES (1, 1, 2, 1); 

而且

INSERT INTO 'configurations' (index, user_id, configDuration, configDurationPerspective) VALUES (1, 1, 2, 'list_remaining'); 

將轉化

INSERT INTO 'configurations' (index, user_id, configDuration, configDurationPerspective) VALUES (1, 1, 2, 2); 

和選擇可能看起來像:

select [index], configDuration, 
case when configDurationPerspective & 1 > 0 then 'list_this_day' else '' end 
+ case when configDurationPerspective & 2 > 0 then 'list_remaining' else '' end as configDurationPerspective 
from configurations 
+0

我編輯了我的帖子,並寫了一些關於如何將值打包到int以及如何選擇它們的建議。如果在選擇它們後將值放入.NET-enum中,則不需要位掩碼,只需將db int值賦予枚舉類型即可。 – mortb

+1

謝謝!這解決了我的問題。 – Apostrofix

2

在MS SQL Server的基本類型的列表不支持相同。但是我們有限制和用戶類型。在這個問題上,你可以看到MySQL的枚舉解決

SQL Server equivalent to MySQL enum data type?

而且你還可以觀察用戶類型(我已經看到了,他們被用於類似用途)

http://msdn.microsoft.com/en-us/library/ms175007.aspx

但作爲這個問題最典型的解決方案,我們(在我們的項目中)使用一些「CodeList/StaticList」表並通過主鍵(int,shortint,tinyint)引用它。