我有以下查询
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
我希望按类别显示以下查询中的数据,其中包含值:Monitor,LCD和Desktop。我认为“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 + ' )
由于
答案 0 :(得分:0)
你必须改变你的@category变量:
DECLARE @category VARCHAR(50) = 'monitor,LCD,Desktop'
为:
DECLARE @category VARCHAR(50) = '''monitor'',''LCD'',''Desktop'''
然后当你在@sql中使用@category时,它也适用于你:
where category IN ('+@category+')
答案 1 :(得分: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
)
并在我的商店程序中:
............... 其中IN类别(选择拆分自 dbo.Split( '', '',@类别))