我正在尝试运行此存储过程,但是它只能运行第一个命令,尽管我能够在存储过程之外运行脚本而没有任何问题
exec GetStoreTransfers '010203','010304'
但是它只返回第一个命令结果:
output
----------------------------------------------------------------------------------------------------
1 file(s) copied.
NULL
(2 row(s) affected)
(0 row(s) affected)
这是存储过程,但仅执行第一个命令:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetStoreTransfers]
(@fromdate nvarchar(8),
@todate nvarchar(8))
AS
DECLARE @from nvarchar(8)
DECLARE @to nvarchar(8)
DECLARE @to_ nvarchar(16)
DECLARE @from_ nvarchar(16)
DECLARE @cmdcopy nvarchar(1000)
DECLARE @command nvarchar(max)
SET @from = @fromdate
SET @to = @todate
SET @from_ = LEFT(CONVERT(char(16), CAST(@from AS date), 105), 5)
SET @to_ = LEFT(CONVERT(char(16), CAST(@to AS date), 105), 5)
SELECT @cmdcopy = /* a specific string*/
SELECT @command = /* a set of commands*/
exec xp_cmdshell @cmdcopy
exec sp_executesql @command
不使用存储过程的整个查询结果如下
output
--------------------------------------------------------------------------------------------------------
1 file(s) copied.
NULL
(2 row(s) affected)
(23654 row(s) affected)
请帮助我克服这个问题,我不想使用SQL Job,这是一个更简单的解决方法,但不是我想要的。
答案 0 :(得分:0)
您需要一个begin
/ end
块:
alter procedure [dbo].[GetStoreTransfers] (
@fromdate nvarchar(8),
@todate nvarchar(8)
) as
begin
declare @from nvarchar(8)
declare @to nvarchar(8)
declare @to_ nvarchar(16)
declare @from_ nvarchar(16)
declare @cmdcopy nvarchar(1000)
declare @command nvarchar(max)
set @from=@fromdate
set @to=@todate
set @from_=left(convert(char(16),cast(@from as date),105),5)
set @to_=left(convert(char(16),cast(@to as date),105),5)
select @cmdcopy = /*A specific String*/
select @command=/*A Set of commands*/
exec xp_cmdshell @cmdcopy
exec sp_executesql @command
end;
答案 1 :(得分:0)
您应尝试使用TRY / CATCH块,并且还应尝试捕获xp_cmdshell结果:
BEGIN TRY
DECLARE @Error INT;
select @cmdcopy = /*A specific String*/
select @command=/*A Set of commands*/
exec @Error = xp_cmdshell @cmdcopy
IF(@Error <> 0)
/*Do some stuff*/
END
exec @Error = sp_executesql @command
IF(@Error <> 0)
/*Do some stuff*/
END
END TRY
BEGIN CATCH
PRINT(ERROR_MESSAGE())
END CATCH
尝试一下,让我们知道:)
致谢!
答案 2 :(得分:0)
很抱歉打扰大家
事实证明,当我执行proc时,我使用了我要从中获取数据的表中不可用的无效参数,现在在更改@fromdate和@todate参数之后它可以正常工作。