2

I want to make a SELECT where I have multiple GUIDs that I use with an IN operator. Why this query does not return all rows where Table1UID equals each item from @table1IDs?

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

SELECT * FROM table1
WHERE Table1UID in (@table1IDs)

It only returns the row where ID is 'b15f554f-90ad-4fab-b3ac-a27bc68f3b21'.

Mention: type of Table1UID is UNIQUEIDENTIFIER

2
  • 1
    It is strange to have string-list of GUID-s - looks like wrong design. Why not simple ID-s (int)? Commented Dec 18, 2014 at 9:29
  • this query I want only for debugging purposes. We use GUID for primary keys. Commented Dec 18, 2014 at 9:35

4 Answers 4

3

The way you stored the value is wrong i guess, do as below

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I chose your solution cause you were the first. Solution of Reza ArabQaeni is almost the same.
3
DECLARE @QRY NVARCHAR(MAX)

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

EXEC SP_EXECUTESQL @QRY 

UPDATE

If you are selecting dynamic values, use the below code and that will work

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

3 Comments

this solution is more useful. @alexa use variable for GUIDs list
Thanks. Your solution worked but when I tried to add another condition where I had another GUID column it returned me conversion issues. However it works as standalone, though hard to maintain. Thanks.
If your values are dynamic and you are selecting the value from a column you can use the updated code @Alexa Adrian
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)

Comments

-1

Split the string into rows and use it in where clause

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)) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.