如何在sql-server中执行多个过程脚本

时间:2015-01-07 09:55:49

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

以下是我在 SQL SERVER

中编写的选择查询
select 'exec pr_tblmaster_split ''tblmaster_'+  Cast(year_id as nvarchar(4000)) +'''' as qry
from  tblmaster
group by year_id 
order by year_id asc

这将返回

qry
-------------------------------------
exec pr_tblmaster_split 'tblmaster_1'
exec pr_tblmaster_split 'tblmaster_2'

所以我的问题是如何使用函数/过程运行返回查询?


我试图将PostgreSQL转换为SQL Server,所以

在PostgreSQL中我可以像这样使用 FOR LOOP

declare 
rw record;
begin
  for rw in 
         select 'select fn_tblmaster_spliting(''tblmaster_'||t.tbl||''');' crTables from (
         select distinct(year_id) tbl from tblmaster order by acyrid asc)t
   loop
         execute rw.crTables;
   end loop;
   end

1 个答案:

答案 0 :(得分:2)

将结果存储在variable中并通过sp_executesql执行。试试这个。

declare @sql nvarchar(max)=''
select @sql+= 'exec pr_tblmaster_split ''tblmaster_'+  Cast(year as nvarchar(4000)) +'''; ' 
from  tblmaster
group by year_id 
order by year_id asc

exec sp_executesql @sql