存储过程参数中的列名称

时间:2015-08-06 18:16:02

标签: sql-server stored-procedures

伙计我有一个存储过程,它根据select查询返回计数。我的问题是我想使程序通用,即如果我将列名传递给存储过程参数,那么它应该根据该列名中的数据返回结果。

ALTER PROCEDURE [dbo].[GetChartValue] 
    -- Add the parameters for the stored procedure here
     @grade char(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    Select COUNT(*) from feedback where 0 in (@grade)
    Select COUNT(*) from feedback where 1 in (@grade)
    Select COUNT(*) from feedback where 2 in (@grade)
    Select COUNT(*) from feedback where 3 in (@grade)
    Select COUNT(*) from feedback where 4 in (@grade)
    Select COUNT(*) from feedback where 5 in (@grade)

END

我做谷歌但没有得到适当的解决方案。任何人都可以建议如何实现它。如果存储过程中有任何错误,请指出。

2 个答案:

答案 0 :(得分:1)

我能想到的唯一方法就是使用sp_executesql 它可以完成这项工作,但我认为你也放弃了存储过程的任何好处

create procedure spGetChartValue (@FieldName nvarchar(50), @Value nvarchar(50) as
begin
    set nocount on

    declare @sql nvarchar(1000) = 'select count(1) from Feedback where ' + quotename(@fieldname) + ' = ' + quotename(@grade, '''')
    exec sp_executesql @sql

end

从你上次的评论中我认为你在找这样的东西?

create procedure spGetChartValue (@Grade nvarchar(50)) as
begin
    set nocount on

    declare @sql nvarchar(1000)

    set @sql = 'select '
    set @sql = @sql + '(select count(1) from Feedback where ' + quotename(@Grade) + ' = 0) as grade_0, '     
    set @sql = @sql + '(select count(1) from Feedback where ' + quotename(@Grade) + ' = 1) as grade_1, '     
    set @sql = @sql + '(select count(1) from Feedback where ' + quotename(@Grade) + ' = 2) as grade_2 '     
    -- and so on...

    exec sp_executesql @sql
end;

答案 1 :(得分:0)

如果你使用动态sql方法,它应该更像是为了防止sql注入。

create procedure spGetChartValue 
(
    @FieldName nvarchar(50)
    , @Value nvarchar(50)
) as
begin
    set nocount on

    declare @sql nvarchar(1000) = 'select count(1) from feedback where ' + QUOTENAME(@FieldName) + ' = @value' 
    exec sp_executesql @sql, N'@Value nvarchar(50)', @Value

end