Click here to Skip to main content
15,912,400 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How do I use a parameter that consist a string in a where statement within a with clause which is bold in the codes. I tried doing that method but its does not work.

I have added a parameter called @param nvarchar(max) already.


SQL
WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
AS
(
    SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
    FROM Sales.SalesOrderHeader
    WHERE SalesPersonID IN ('+ @param +')
)
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM Sales_CTE
GROUP BY SalesYear, SalesPersonID
Posted

You can use parameters in a WITH clause just like in a traditional statement. The problem in the example is the IN operator which requires a list of values.

Have a look at this tip how you can use a parameter with IN: Using comma separated value parameter strings in SQL IN clauses[^]
 
Share this answer
 
you can use dynamic sql and execute it
SQL
DECLARE @SQLQuery AS NVARCHAR(MAX)
SET @SQLQuery = 'SELECT * FROM table1 WHERE EmployeeID in(' + @param +')'
EXECUTE(@SQLQuery)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900