我有一个返回网格结果的存储过程。我将@idCC
参数传递给SQL查询时遇到了一些基本问题,如图所示。我知道如果删除数值中的参数和硬编码,SQL就可以工作。如何允许查询将@idCC
读取到显示的查询?
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_CC_ContactGroupList]
(@idCC int)
AS
BEGIN
DECLARE @ListOfGroups VARCHAR(MAX) =
(STUFF((SELECT DISTINCT ',' + QUOTENAME(GroupName)
FROM dbo.CC_Groups
WHERE IsContactGroup = '1'
FOR XML PATH('')), 1, 1, ''));
DECLARE @sql VARCHAR(MAX) = ('SELECT *
FROM
(SELECT
dbo.CC_Contacts.idCC,
dbo.CC_Groups.GroupName AS gName,
''X'' AS IsInGroup
FROM
dbo.CC_ContactGroups
INNER JOIN
dbo.CC_Groups ON dbo.CC_ContactGroups.idGroup = dbo.CC_Groups.idGroup
INNER JOIN
dbo.CC_Contacts ON dbo.CC_ContactGroups.idCC = dbo.CC_Contacts.idCC
WHERE
dbo.CC_Contacts.idCC = '''+@idCC+''') AS x
PIVOT (MAX(IsInGroup)
FOR gName IN(' + @ListOfGroups + ')) as p');
EXEC(@sql);
END
答案 0 :(得分:1)
在存储过程[dbo].[sp_CC_ContactGroupList]
中,替换
dbo.CC_Contacts.idCC = '''+@idCC+'''
与
dbo.CC_Contacts.idCC = '''+cast(@idCC as varchar)+'''
现在它会显示@idCC