1

I would like to write an IN statement when setting the RECEIPTIDS variable, so that I can pass multiple values in that format into my query. I have tried the following:

DECLARE @RECEIPTIDS VARCHAR(2000)
SET @RECEIPTIDS = ('R00013','R00028')

However, I get the error:

Incorrect syntax near ','.

0

4 Answers 4

5

You need table variable or temp table.

DECLARE @RECEIPTIDS TABLE(val VARCHAR(100))
Insert into @RECEIPTIDS values ('R00013'), ('R00028')

You can use it in IN as

where field IN (Select val from @RECEIPTIDS)
Sign up to request clarification or add additional context in comments.

4 Comments

I get the following: Must declare the scalar variable
I am able to execute it successfully. I suspect some typos somewhere.
No i cannot execute it. I wrapped square brackets around the variable but still no luck
Try to first execute above example. If it does not execute then i suspect SQL server version issue
3

You need extra single qoutes.

    create table MyTable
    (
       ID varchar(50) 
    )
    insert into MyTable values('R00013')
    insert into MyTable values('R00028')
    insert into MyTable values('R00015')

    DECLARE @RECEIPTIDS VARCHAR(2000)
    SET @RECEIPTIDS = ('''R00013'',''R00028''')
    DECLARE @QUERY VARCHAR(100)

    SET @QUERY='SELECT * 
    from MyTable 
    where ID IN ('+@RECEIPTIDS+')'
    EXEC (@QUERY)

Edited: Use it with Dynamic query.

3 Comments

that does not answer the question, because this results in a variable holding a single value whereas OP asked about multiple values in one variable, you would need to include a use of a function to split that string into a sequence of values to provide a complete example
@DrCopyPaste updated the answer , OP can use it with dynamic query
Nice one! Here's also a fiddle if anyone wants to try that out online. sqlfiddle.com/#!6/c6627/1
3

Use temporary array or temporary List

DECLARE @ListofIDs TABLE(IDs VARCHAR(100))
INSERT INTO @ListofIDs VALUES('a'),('10'),('20'),('c'),('30'),('d')
SELECT IDs FROM @ListofIDs;

1 Comment

I get the following error: Must declare the scalar variable
0

Didn't work for me either but this did:

DECLARE @RECEIPTIDS TABLE(val VARCHAR(100))
Insert into @RECEIPTIDS values ('R00013'), ('R00028')

where field IN (Select val from @RECEIPTIDS)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.