0

我想在 SQL Server 存储过程中生成一个 select 语句。我在 SQL 参数中有列名。

我正在尝试使用所选列名以编程方式生成 select 语句,但似乎无法在存储过程中找到正确的语法。

CREATE PROCEDURE dbo.aProc
     @testCondition int,
     @colCount int,
     @column_1 varchar(100) = null,
     ....
    @column_40 varchar(100) null
AS
  DECLARE @qry nvarchar(3000)
  DECLARE @Iterator int

  SET @testtype = 2
  SET @Iterator = 0
  SET @qry  ='SELECT '

  WHILE (@Iterator < @colCount-1)
    BEGIN
        SET @qry = @qry + ''+@column_''+CAST(@Iterator as varchar(2))+',''
        Set @Iterator = @Iterator + 1
    END


  SET @qry = @qry + ''@column_+CAST(@colCount as varchar(2)) FROM aTable where aCol = @testCondition 
4

2 回答 2

0
CREATE PROCEDURE dbo.aProc
    @tablename varchar(100),
     @testCondition int,
     @colCount int,
     @column_1 varchar(100) = '',
     ....
    @column_40 varchar(100) ''
AS
BEGIN
if object_id('tempdb..#t') is not null
drop table #t


select 
table_name
,column_name
into #t
from information_schema.columns
where table_name=@tablename
and column_name in 
(@column_1,@column_2,@column_3,@column_4,@column_5
.....
@column_36,@column_37,@column_38,@column_39,@column_40)

select 
  'select '+
  stuff((
    select ', ' + 'isnull('+t2.column_name+','''') as' +t2.column_name+CHAR(10)
    from #t t2
    where t2.table_name = #t.table_name
    for xml path (''))
,1,2,'')+' from ' +#t.table_name
from #t
group by #t.table_name

END

我不是LOOP的崇拜者。事实上我讨厌循环查询。

于 2013-10-19T14:08:31.870 回答
0

这看起来是个坏主意(强制性的 sql 注入链接),但有可能的替代方案

要回答这个问题,然后做这样的事情。

DECLARE @sql VARCHAR(MAX)

SET @sql = 'SELECT ' + 
               ISNULL(@col1, '') + ', ' +
               ISNULL(@col2, '') + ', ' +
               ISNULL(@col3, '') + ', ' +
               ISNULL(@col4, '') + ', ' +
               ISNULL(@col5, '') + ', ' +
               -- ...
           'FROM tbl WHERE ' ...

这样做 - 或者也许正如评论所暗示的那样 - 这样做比搞乱循环(顺便说一句,你很不适应)更省力。

老实说,尽管使用内联函数似乎会更好

CREATE FUNCTION dbo.vSomeTable
    (@id INT)
RETURNS TABLE
AS
RETURN (
    SELECT * FROM tbl WHERE condition = @id
)

然后让用户做

SELECT col1, col2, col2 FROM dbo.vSomeTable(4)

这比

EXEC dbo.aProc @condition=1, @col1='col1', @col2='col2'
于 2013-10-19T13:37:35.857 回答