如何在with
子句中的where语句中使用包含字符串的参数,该子句在代码中以粗体显示。我尝试过这种方法,但它没有用。
我已经添加了一个名为@param nvarchar(max)的参数。
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
答案 0 :(得分:2)
您必须使用表变量而不是NVARCHAR
,例如:
DECLARE @param TABLE (id int)
INSERT INTO @param VALUES (1), (2), (3)
;WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
AS
(
SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
FROM Sales.SalesOrderHeader
WHERE SalesPersonID IN (SELECT id FROM @param)
)
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM Sales_CTE
GROUP BY SalesYear, SalesPersonID
或者,如果@param
是逗号分隔的数字列表,则可以使用拆分字符串函数。然后你可以像这样使用IN
运算符:
WHERE SalesPersonID IN (SELECT id FROM dbo.fnSplitString(@param, ',')
Here是分裂字符串函数的一个很好的参考。
答案 1 :(得分:0)
Declare @param varchar(max) = 'some value'
;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
或者您可以实现此动态查询
答案 2 :(得分:0)
您可以将查询更改为字符串查询,然后执行它。
DECLARE @SQLQuery VARCHAR(MAX)
SET @SQLQuery = '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'
EXEC(@SQLQuery)
答案 3 :(得分:0)
如Jonathan所述,您可以在此处使用动态查询,如下所示。
DECLARE @param VARCHAR(MAX)
DECLARE @query NVARCHAR(MAX)
SET @param = '1,2,5'
SET @query = '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'
EXEC SP_EXECUTESQL @query