我有一个 SQL 存储过程“A”,它验证给定帐户的某些银行帐户信息,它接受帐号作为参数“arg1”
我想对另一个表XXX的X 列中存在的所有值执行该过程(Accounts 表中存在的所有银行账户)
我不确定这样的事情是否可行
exec A @arg1 = X from XXX
提前致谢!
我有一个 SQL 存储过程“A”,它验证给定帐户的某些银行帐户信息,它接受帐号作为参数“arg1”
我想对另一个表XXX的X 列中存在的所有值执行该过程(Accounts 表中存在的所有银行账户)
我不确定这样的事情是否可行
exec A @arg1 = X from XXX
提前致谢!
不,没有您想要运行它的批量 EXEC。
选项 1:手动生成和运行。复制结果,粘贴回 SSMS 并执行。
select 'exec A @arg1 = ' + quotename(X,'''') + ';'
from XXX
选项 2:生成批处理并使用动态 SQL 运行。
declare @sql nvarchar(max);
set @sql = '';
select @sql = @sql + 'exec A @arg1 = ' + quotename(X,'''') + ';'
from XXX;
exec (@sql);
选项3:循环运行
declare @x varchar(max);
select top(1) @x = X from xxx where X is not null order by X;
while @@rowcount > 0
begin
    exec sp_executesql N'exec A @arg1=@x;', N'@x varchar(max)', @x=@x;
    select top(1) @x = X from xxx where X > @x order by X;
end;
通常以基于集合的方式处理事情会更好,但是如果您确实需要为结果集中的每一行按顺序执行某些操作,那么可以使用游标:
declare cur cursor for
select X from XXX
declare @x int
open cur
fetch next from cur into @x
while @@FETCH_STATUS = 0
BEGIN
    exec A @x
    fetch next from cur into @x
END
尝试使用带有 Coalesce 命令的动态查询。下面的查询对 XXX 表的 X 列的数据执行 A 存储过程。
-- Create Dynamic Query
DECLARE @ValidateAccountCommand VARCHAR(MAX) 
SELECT @ValidateAccountCommand = COALESCE(@ValidateAccountCommand + 
                                            '; EXEC A ', 
                                             'EXEC A ') 
                                + CONVERT(NVARCHAR,XxxData.X)
FROM 
(SELECT X FROM XXX) XxxData
PRINT @ValidateAccountCommand
EXECUTE (@ValidateAccountCommand)