0

我有以下查询

DECLARE @category VARCHAR(50) = 'monitor,LCD,Desktop' 
DECLARE @sql nvarchar(4000)

IF @category IS NOT NULL 
BEGIN
SELECT @sql = 'SELECT *, 
CASE 
    WHEN Aging > 90 THEN ''> 90'' 
    ELSE
        CASE 
            WHEN Aging > 60 THEN ''61-90''
            ELSE 
                CASE 
                    WHEN Aging > 30 THEN ''31-60''
                    ELSE ''<=30''
                END
        END
END AS AgingCat, Pct*100 AS Percentage FROM dbo.vwPartnerProductAging

where category IN ('+@category+') 
ORDER BY PartnerName, Category, [Description]'

END

exec sp_executesql @sql, N'@category VARCHAR(50) ', @category

我想按具有值的类别显示来自以下查询的数据:显示器、LCD 和桌面。我在“WHERE blablabla”中解决问题

我有两个条件我试过。

第一个条件

从我用值声明@category 时显示的代码中显示它的错误

“无效的列名监视器”

“无效的列名 LCD”

“无效的列名桌面”

第二个条件

我为

where category IN ('''+@category+''') 

如果我只添加一个值,它就可以工作,但是如果我声明 @category 有多个值,它不会显示任何内容但没有错误


如果我将值直接放在“WHERE blablabla”上,它就可以正常工作。

工作条件

DECLARE @category VARCHAR(50) = 'monitor,LCD,Desktop' 
DECLARE @sql nvarchar(4000)

IF @category IS NOT NULL 
BEGIN
SELECT @sql = 'SELECT *, 
CASE 
    WHEN Aging > 90 THEN ''> 90'' 
    ELSE
        CASE 
            WHEN Aging > 60 THEN ''61-90''
            ELSE 
                CASE 
                    WHEN Aging > 30 THEN ''31-60''
                    ELSE ''<=30''
                END
        END
END AS AgingCat, Pct*100 AS Percentage FROM dbo.vwPartnerProductAging

where category IN (''Monitor'',''LCD'',''Desktop'') 
ORDER BY PartnerName, Category, [Description]'

END

exec sp_executesql @sql, N'@category VARCHAR(50) ', @category

我想改变:

where category IN (''Monitor'',''LCD'',''Desktop'') 

至:

where category IN ( ' + @category + ' )

谢谢

4

2 回答 2

0

谢谢@st mnmn,但我已经解决了这个问题

我正在使用用分隔符“,”分割字符串的函数

所以@category 的输入必须有带分隔符“,”的值

示例输入

@category= 'LCD,Monitor,Desktop'

我使用的功能

FUNCTION [dbo].[Split] (@sep char(1), @s varchar(2000))
RETURNS table
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
  SELECT 1, 1, CHARINDEX(@sep, @s)
  UNION ALL
  SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
  FROM Pieces
  WHERE stop > 0
)
SELECT pn,
  SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS split
FROM Pieces

)

在我的商店程序中:

...... where Category IN (select split from dbo.Split('','',@category))

于 2012-05-04T06:01:00.800 回答
0

你必须改变你的@category变量:

DECLARE @category VARCHAR(50) = 'monitor,LCD,Desktop'

至:

DECLARE @category VARCHAR(50) = '''monitor'',''LCD'',''Desktop'''

然后当您在@sql 中使用@category 时,它也会对您有用:

where category IN ('+@category+')
于 2012-05-03T07:56:16.830 回答