您可以使用XML架构在SQL Server中创建枚举类型。
例如颜色。
create xml schema collection ColorsEnum as '
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Color">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Red"/>
<xs:enumeration value="Green"/>
<xs:enumeration value="Blue"/>
<xs:enumeration value="Yellow"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:schema>';
这样就可以使用类型的变量或参数xml(dbo.ColorsEnum)
。
declare @Colors xml(dbo.ColorsEnum);
set @Colors = '<Color>Red</Color><Color>Green</Color>'
如果您尝试添加不是颜色的东西
set @Colors = '<Color>Red</Color><Color>Ferrari</Color>';
你得到一个错误。
Msg 6926, Level 16, State 1, Line 43
XML Validation: Invalid simple type value: 'Ferrari'. Location: /*:Color[2]
像这样构造XML可能有点乏味,因此您可以例如创建一个也包含允许值的帮助程序视图。
create view dbo.ColorsConst as
select cast('<Color>Red</Color>' as varchar(100)) as Red,
cast('<Color>Green</Color>' as varchar(100)) as Green,
cast('<Color>Blue</Color>' as varchar(100)) as Blue,
cast('<Color>Yellow</Color>' as varchar(100)) as Yellow;
并像这样使用它来创建枚举。
set @Colors = (select Red+Blue+Green from dbo.ColorsConst);
如果要从XML Schema动态创建视图,则可以使用此查询提取颜色。
select C.Name
from (select xml_schema_namespace('dbo','ColorsEnum')) as T(X)
cross apply T.X.nodes('//*:enumeration') as E(X)
cross apply (select E.X.value('@value', 'varchar(100)')) as C(Name);
枚举当然也可以用作功能和过程的参数。
create function dbo.ColorsToString(@Colors xml(ColorsEnum))
returns varchar(100)
as
begin
declare @T table(Color varchar(100));
insert into @T(Color)
select C.X.value('.', 'varchar(100)')
from @Colors.nodes('Color') as C(X);
return stuff((select ','+T.Color
from @T as T
for xml path('')), 1, 1, '');
end
create procedure dbo.GetColors
@Colors xml(ColorsEnum)
as
select C.X.value('.', 'varchar(100)') as Color
from @Colors.nodes('Color') as C(X);
declare @Colors xml(ColorsEnum) = '
<Color>Red</Color>
<Color>Blue</Color>
';
select dbo.ColorsToString(@Colors);
set @Colors = (select Red+Blue+Green from dbo.ColorsConst);
exec dbo.GetColors @Colors;