SQL字段分割后行转列
我们经常遇到SQL字段的值是通过某种字符分割组合的字符串,类如"a|b|c|d"
我们需要把这个字段的值分割后行转列查询出来,可以用下面的语句实现,
SQL Server
字段Permission_DefaultZone的值是用字符'|'分割的
SELECT b.[Permission_DefaultZone] FROM (SELECT [Permission_DefaultZone]=CAST('<v>'+REPLACE([Permission_DefaultZone],'|','</v><v>')+'</v>' AS xml) FROM NewRetail_Permission WHERE Permission_ID = {0}) a OUTER APPLY (SELECT [Permission_DefaultZone]=T.C.value('.','varchar(50)') FROM a.[Permission_DefaultZone].nodes('/v') AS T(C)) b
查询的结果如下:
下面的语句就是用上面的语句进行IN查询,如下:
SELECT Device_ID as DeviceID FROM NewRetail_Device where Device_Address in( SELECT b.[Permission_DefaultZone] FROM (SELECT [Permission_DefaultZone]=CAST('<v>'+REPLACE([Permission_DefaultZone],'|','</v><v>')+'</v>' AS xml) FROM NewRetail_Permission WHERE Permission_ID = {0}) a OUTER APPLY (SELECT [Permission_DefaultZone]=T.C.value('.','varchar(50)') FROM a.[Permission_DefaultZone].nodes('/v') AS T(C)) b )