0

This may be a very basic question, but I have been struggling with this.

I have a SSMS query that I'll be using multiple times for a large set of client Ids. Its quite cumbersome to have to amend the parameters in all the where clauses every time I want to run it.

For simplicity, I want to convert a query like the one below:

SELECT
ID,
Description

From TestDb

Where ID in ('1-234908','1-345678','1-12345')

to a query of the format below so that I only need to change my variable field once and it can be applied across my query:

USE TestDb

DECLARE @ixns NVARCHAR(100)

SET @ixns = '''1-234908'',''1-345678'',''1-12345'''

SELECT 
ID,
Description

From TestDb

Where ID IN @ixns

However, the above format doesn't work. Can anyone help me on how I can use a varchar/string variable in my "where" clause for my query so that I can query multiple IDs at the same time and only have to adjust/set my variable once?

Thanks in advance :D

1

3 Answers 3

1

The most appropriate solution would be to use a table variable:

DECLARE @ixns TABLE (id NVARCHAR(100));
INSERT INTO @ixns(id) VALUES
('1-234908'),
('1-345678'),
('1-12345');

SELECT ID, Description
FROM TestDb
WHERE ID IN (SELECT id FROM @ixns);
Sign up to request clarification or add additional context in comments.

Comments

0

You can load ids to temp table use that in where condition

USE TestDb

DECLARE @tmpIDs TABLE
    (     
      id VARCHAR(50)     
    )

insert into @tmpIDs values ('1-234908')
insert into @tmpIDs values ('1-345678')
insert into @tmpIDs values ('1-12345')



SELECT 
ID,
Description
From TestDb
Where ID IN (select id from @tmpIDs)

Comments

0

The most appropriate way is to create a table type because it is possible to pass this type as parameters.

1) Creating the table type with the ID column.

    create type MyListID as table 
    (
        Id int not null
    )
    go

2) Creating the procedure that receives this type as a parameter.

    create procedure MyProcedure
                        (
                            @MyListID as MyListID readonly
                        )
    as

        select 
            column1,
            column2
            ...
        from
            MyTable
        where
            Id in (select Id from @MyListID)

3) In this example you can see how to fill this type through your application ..: https://stackoverflow.com/a/25871046/8286724

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.