如何在拥有GUID列表时从表中选择行?

时间:2014-12-18 09:20:11

标签: sql sql-server

我想创建一个SELECT,其中我有一个与IN运算符一起使用的多个GUID。 为什么此查询不返回Table1UID等于@ table1IDs中每个项目的所有行?

DECLARE @table1IDs NVARCHAR(100)
SET @table1IDs  = 'b15f554f-90ad-4fab-b3ac-a27bc68f3b21, 72213eb7-1041-408c-9ea1-35a667285c9b'

SELECT * FROM table1
WHERE Table1UID in (@table1IDs)

它只返回ID为'b15f554f-90ad-4fab-b3ac-a27bc68f3b21'的行。

提及:Table1UID的类型是UNIQUEIDENTIFIER

4 个答案:

答案 0 :(得分:3)

DECLARE @QRY NVARCHAR(MAX)

SET @QRY = 'SELECT * FROM table1 WHERE Table1UID IN (' + @table1IDs + ')'

EXEC SP_EXECUTESQL @QRY 

更新

如果您要选择动态值,请使用以下代码并使用

SELECT @table1IDs = COALESCE (@table1IDs + ',[' + YOURCOLUMN + ']', 
              '[' + YOURCOLUMN + ']')
               FROM    (SELECT DISTINCT YOURCOLUMN FROM YOURTABLE) PV  
               ORDER BY YOURCOLUMN 

答案 1 :(得分:3)

您存储值的方式是错误的我猜,请按以下方式执行

declare @temp table(ID nvarchar(1000))
insert into @temp values('b15f554f-90ad-4fab-b3ac-a27bc68f3b21')
insert into @temp values('72213eb7-1041-408c-9ea1-35a667285c9b')

SELECT * FROM table1
WHERE Table1UID in (select ID from @temp)

答案 2 :(得分:1)

DECLARE @table1IDs table(id uniqueidentifier)
insert into @table1IDs(id) values 
('b15f554f-90ad-4fab-b3ac-a27bc68f3b21')
,('72213eb7-1041-408c-9ea1-35a667285c9b')

select * from table1 where Table1UID in (select id from @table1IDs)

答案 3 :(得分:-1)

Split将字符串分成行并在where子句

中使用它
DECLARE @table1IDs NVARCHAR(100)
SET @table1IDs  = 'b15f554f-90ad-4fab-b3ac-a27bc68f3b21, 72213eb7-1041-408c-9ea1-35a667285c9b'


SELECT *
FROM   table1
WHERE  Table1UID IN(SELECT Rtrim(Ltrim(Split.a.value('.', 'VARCHAR(100)')))
                          FROM   (SELECT Cast ('<M>' + Replace(@table1IDs, ',', '</M><M>') + '</M>' AS XML) AS Data) AS A
                                 CROSS APPLY Data.nodes ('/M') AS Split(a))