2012-11-05 61 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)引用它。