带有exec xp_create_subdir的Sql Server Cursor

时间:2013-11-05 15:25:42

标签: sql-server

我正在尝试遍历SQL Server数据库上的所有现有帐户,并使用xp_create_subdir创建单个帐户文件夹。但是,我知道我的工作没有用,因为我试图将变量作为参数的一部分传递。这是我的代码:

declare @id int

declare crsr cursor LOCAL FAST_FORWARD for

select  Id
from AccountModels
where Active = 1
and Id in (select Account_Id from AccountPhotoModels)
order by Id

open crsr
fetch crsr into @id

While (@@fetch_status = 0)
begin

   exec master.dbo.xp_create_subdir 'C:\inetpub\wwwroot\media\images\accounts\' + @id

fetch crsr into @id
end
close crsr
deallocate crsr

有没有人知道如何在游标中调用该系统SP,就像我上面尝试的那样?

2 个答案:

答案 0 :(得分:0)

只需将您要传递的值组合为一个单独的步骤:

...
declare @path varchar(max)
open crsr
fetch crsr into @id

While (@@fetch_status = 0)
begin
   set @path = 'C:\inetpub\wwwroot\media\images\accounts\' + @id
   exec master.dbo.xp_create_subdir @path

fetch crsr into @id
end
close crsr
deallocate crsr

对于每个参数,您可以传递变量 - 但您无法计算表达式来获取该值。

答案 1 :(得分:0)

只要@id不是varchar(但int),您也必须执行此更改:

FROM:

set @path = 'C:\inetpub\wwwroot\media\images\accounts\' + @id

TO:

set @path = 'C:\inetpub\wwwroot\media\images\accounts\' + Cast(@id as varchar)