如何为此编写动态SQL?

时间:2011-05-27 19:56:24

标签: sql sql-server sql-server-2008 stored-procedures dynamic-sql

我需要编写一个只有执行语句的过程。

示例:

Create Procedure dbo.allSPExecute( @id int)
as
begin

EXEC dbo.tic @day= 7,@name = 'Gname',@Type = 'Utype'
EXEC dbo.tic @day= 7,@name = 'tname',@Type = 'Utype'
EXEC dbo.gtype @day = 7,@Tname = 'UName_By',@Udept = 'Dept'

End

我有50多个这样的陈述。我有一个表是Lookup:

ID  Name        SCol      Dcol       IOrd
1   dbo.tic     Gname     @name       1
1   dbo.tic     tname     @name       2
1   dbo.tic     Utype     @Type       1
1   dbo.tic     Utype     @Type       2
2   dbo.gtype   UName_By  @Tname      1
2   dbo.gtype   Dept      @Udept      1

有没有办法使得如果我传递ID,那么它将获取Lookup表中的值并执行该过程。有人可以帮忙吗?

编辑:更改了Lookpup表中的数据和创建过程

3 个答案:

答案 0 :(得分:4)

最简单的解决方案 - 使您的存储过程如下:

Create Procedure dbo.allSPExecute( @id int)
as

DECLARE @SQL varchar(max)

SET @SQL = 'USE MyDB'

SELECT @SQL = @SQL +
'EXEC ' + t.Name + ' @day = 7,' + t.Dcol + ' = ''' + t.Scol + ''
FROM MyTable t
WHERE t.id = @ID

EXEC (@SQL)

答案 1 :(得分:1)

这是一个不需要游标的解决方案。我使用FOR XML关键字将字符串连接在一起。我在两个地方这样做 - 一次用于连接参数列表,一次用于连接所有单独的exec语句。我没有测试过这个,但我认为这应该比使用游标快得多

CREATE PROCEDURE dbo.allSPExecute( @id INT ) 
AS  
BEGIN   
  DECLARE @query VARCHAR(MAX);   
  SELECT @query =   (
    SELECT ExecPart + ' ' + SUBSTRING(Params,2,LEN(Params)) + CHAR(10)
    FROM
    (
      SELECT 
        ExecPart ='EXEC ' +(SELECT TOP 1 Name FROM MyTable WHERE ID = @id) ,
        Params = (SELECT ', ' + Dcol + ' = ' + Scol 
                  FROM MyTable t1 WHERE ID = @id AND t1.IOrd = t.IOrd FOR XML PATH(''))
      FROM MyTable t
      WHERE ID = @id
      GROUP BY IOrd
    ) t
    FOR XML PATH('')   
  ) 

  EXEC (@query) 
END

答案 2 :(得分:0)

这是一个从头开始编写并且未经测试的游标示例:

declare @dynsql as nvarchar(300)
declare @tname as nvarchar(100)
declare @tscol as nvarchar(100)
declare @tdcol as nvarchar(100)

set @dynsql = ''

declare ticker as cursor for select Name, SCol, DCol from Lookup
open ticker
fetch next from ticker into @tname, @tscol, @tdcol

while @@FETCH_STATUS = 0
BEGIN

set @dynsql = 'EXEC ' + @tname + ' @day=7, ' + @tdcol + '=''' + @tscol + ''''

exec(@dynsql)

FETCH NEXT from ticker into @tname, @tscol, @tdcol
END

close ticker
deallocate ticker