0

I have the following part of a query:

Where id in (1,2,3) And country in('France','Italy','Spain')

I want to declare 2 variables and do it like:

Where id in (idsVaraible) And country in(countriesVriable)

It is more like substituting sql code in sql code to make my long query readable and more useful, is there any way to do this?

I think it's more like eval in java script.

1
  • 1
    How about adding a temp table variable and assigning? Commented Apr 6, 2013 at 12:03

2 Answers 2

1

Well if you need to pass these sets in as strings, one way would be dynamic SQL:

DECLARE @ids VARCHAR(32) = '1,2,3';
DECLARE @countries VARCHAR(2000) = 'France,Italy,Spain';

DECLARE @sql NVARCHAR(MAX) = N'SELECT ... FROM ...
  WHERE id IN (' + @ids + ') AND country IN ('''
  + REPLACE(@countries, ',',''',''') + ''');';

PRINT @sql;
-- EXEC sp_executesql @sql;

Another way would be table-valued parameters. First create these types in your database:

CREATE TYPE dbo.TVPids AS TABLE(ID INT);
CREATE TYPE dbo.TVPcountries AS TABLE(Country VARCHAR(255));

Now your stored procedure can take these types as input:

CREATE PROCEDURE dbo.whatever
  @i dbo.TVPids READONLY,
  @c dbo.TVPcountries READONLY
AS
BEGIN
  SET NOCOUNT ON;

  SELECT ... FROM dbo.yourtable AS t
    INNER JOIN @i AS i ON i.ID = t.ID
    INNER JOIN @c AS c ON c.country = t.country;
END
GO

Now your app can pass these two parameters in as sets (e.g. from a DataTable) instead of building a comma-separated string or handling multiple parameters.

Sign up to request clarification or add additional context in comments.

6 Comments

the first part is all i wanted :)
@user1590636 great, but you should learn about the second part as well. Sets are much more powerful and flexible than JSON strings and dynamic SQL.
@user1590636 of course they do. What makes you think a comma-separated string works and a set doesn't? Can you provide an example where you think this will be a problem (preferably as a different question)?
sure, the idea is i have a group by clauses to group by month week querter and year also by different dynamic number of columns, do you think working with sets would be a better option?
@user1590636 not enough information to answer your question, sorry.
|
1

Please try using temp table variables:

DECLARE @tblID as TABLE(ID INT)
DECLARE @tblCountry as TABLE(Country NVARCHAR(50))

INSERT INTO @tblID VALUES (1),(2),(3)
INSERT INTO @tblCountry VALUES ('France'),('Italy'),('Spain')

WHERE id in (select ID from @tblID) And country in(select Country from @tblCountry)

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.