SQL Server存储过程 - 参数

时间:2017-02-09 17:00:17

标签: sql sql-server stored-procedures

我有一个返回网格结果的存储过程。我将@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

1 个答案:

答案 0 :(得分:1)

在存储过程[dbo].[sp_CC_ContactGroupList]中,替换

dbo.CC_Contacts.idCC = '''+@idCC+'''

dbo.CC_Contacts.idCC = '''+cast(@idCC as varchar)+'''

现在它会显示@idCC