2

Question:

How to do this:

DECLARE @StateUID varchar(max)  

SET @StateUID = 'E8812237-2F3B-445E-8EEF-020E0B6F6A53, 66E57225-642F-45B5-8E5D-070F2D1CF99D, 751C615B-EB9C-4D25-955D-0E0EB3CD05A2' 


SELECT StateFullName, StateAbbrv, StateID
FROM tblStates 
WHERE StateUID IN ( @StateID )

Doing string.join as shown below doesn't help as well:

SET @StateUID = '''E8812237-2F3B-445E-8EEF-020E0B6F6A53'', ''66E57225-642F-45B5-8E5D-070F2D1CF99D'', ''751C615B-EB9C-4D25-955D-0E0EB3CD05A2''' 




I've now moved it into dynamic SQL, where it works.

But this is extremely error-prone, annoying and time-consuming, so I wanted to ask whether there is any non-insane way of doing this (without temp tables, functions etc.) ?

Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442

3 Answers3

3

In this case it seems you can use 'like'

DECLARE @QueryUIDs  varchar(MAX)
SET @QueryUIDs = '''E8812237-2F3B-445E-8EEF-020E0B6F6A53'', ''66E57225-642F-45B5-8E5D-070F2D1CF99D'', ''751C615B-EB9C-4D25-955D-0E0EB3CD05A2''' 

SELECT StateFullName, StateAbbrv, StateUID
FROM tblStates 
WHERE @QueryUIDs LIKE '%' + CAST(StateUID AS CHAR(36)) + '%'
Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
t-clausen.dk
  • 43,517
  • 12
  • 59
  • 92
  • Nice solution by problem inversion. Elegant and yet soooo simple. It lacked a cast to varchar. I added the details. Everybody else, note that @QueryUIDs is actually a stored procedure parameter, passed by JOIN(Parameters!in_location_new.Value, "' , '") – Stefan Steiger Jul 19 '11 at 09:17
1

One option is to parse the comma delimited string into a subquery. The code below assumes that you can remove spaces from the @StateUID string and that StateID is a unique identifier:

DECLARE @StateUID varchar(max), @xml xml  

SET @StateUID = 'E8812237-2F3B-445E-8EEF-020E0B6F6A53,' + 
    '66E57225-642F-45B5-8E5D-070F2D1CF99D,' + 
    '751C615B-EB9C-4D25-955D-0E0EB3CD05A2' 

SET @xml = '<root><r>' + replace(@StateUID,',','</r><r>') + '</r></root>'

SELECT StateFullName, StateAbbrv, StateID
FROM tblStates 
WHERE StateID IN ( 
    SELECT
      CONVERT(uniqueidentifier, t.value('.','varchar(36)')) as [id]
    FROM @xml.nodes('//root/r') as a(t)
) 

There are many great string splitting functions but using XML is my favorite.

Community
  • 1
  • 1
8kb
  • 10,956
  • 7
  • 38
  • 50
0

if you don't like temp tables and arrays, you can use more than one variable:

DECLARE @StateUID_1 varchar(max)  
DECLARE @StateUID_2 varchar(max)  
DECLARE @StateUID_3 varchar(max)  

SET @StateUID_1 = 'E8812237-2F3B-445E-8EEF-020E0B6F6A53'
SET @StateUID_2 = '66E57225-642F-45B5-8E5D-070F2D1CF99D'
SET @StateUID_3 = '751C615B-EB9C-4D25-955D-0E0EB3CD05A2' 


SELECT StateFullName, StateAbbrv, StateID
FROM tblStates 
WHERE StateUID IN ( @StateUID_1, @StateUID_2, @StateUID_3 )
ypercubeᵀᴹ
  • 113,259
  • 19
  • 174
  • 235