存储过程不返回值

时间:2014-01-20 12:29:13

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

我创建了一个采用UNC路径的存储过程,根据日期附加子文件夹字符串,然后执行xp_cmdshell 'Dir '以检查目录中有多少文件。

不幸的是,它似乎没有向我调用的sql返回一个值。

这是存储过程:

create procedure getDirFileCount (
    @sUNCPath Varchar(500),
    @countFiles int OUTPUT
    )

AS
    BEGIN
        declare @files table (ID int IDENTITY, FileName varchar(100)) 
        declare @saveDir varchar(250), @Cmd varchar(500)
        declare @Count int

    -- get the correct path for today's generated files in format \Year\Month\dd.mm.yyyy...     
        set @saveDir =@sUNCPath 
        + cast(YEAR(GETDATE()) as varchar(4)) 
        + '\'  + datename(month, GETDATE()) 
        + '\'+SUBSTRING(CONVERT(CHAR(20), GETDATE(), 101),4, 2) 
        + '.' + LEFT(CONVERT(CHAR(20), GETDATE(), 101), 2)
        + '.' + SUBSTRING(CONVERT(CHAR(20), GETDATE(), 101),7, 4)  

        -- using quoted identifier for the long string UNC path
        set @Cmd= 'dir "' + @saveDir + '" /b'

        insert into @files execute xp_cmdshell @cmd
        select @Count= COUNT(*) from @files     

        SET @countFiles=@Count

        RETURN @countFiles
        --print @countFiles
    END

以下是我用来调用存储过程的代码:

declare @DaysOffset int=0, @I int =0

DECLARE @tmpLetterTbl TABLE (
    [docID] [int] IDENTITY(1,1) NOT NULL,
    [docRef] [varchar](50) NULL,
    [saveDir] [varchar](4000) NULL,
    [totalLettersExpected] [int] NULL,
    [actualLetters] [int] NULL,
    [EQRecordCount] [int] NULL
) 

insert @tmpLetterTbl SELECT distinct docRef, 
    saveDir=max(Save_Directory),
    COUNT(*) as 'Total Letters', null, null
  FROM [alpsMaster].[dbo].[uExtractMonitor]
  where YPTMPID<>0
  group by docRef
  order by 1,2

-- Get the number of rows in the looping table
DECLARE @RowCount INT,@Date varchar(20)

set @Date=rtrim(CONVERT( CHAR(12), getDate()-@DaysOffset, 106)) --'29 Oct 2013'
SET @RowCount = (SELECT COUNT(docID) FROM @tmpLetterTbl) 

WHILE (@I <= @RowCount)
    BEGIN

        DECLARE @docRef VARCHAR(10)
        DECLARE @saveDir VARCHAR(500)
        DECLARE @letterCount int

         -- Get the data from table and set to variables
         SELECT @docRef = docref FROM @tmpLetterTbl WHERE docID = @I
         SELECT @saveDir = saveDir FROM @tmpLetterTbl WHERE docID = @I      

    update @tmpLetterTbl set actualLetters = 0 where docRef=@docRef         
    exec getDirFileCount @SaveDir, @letterCount 

    print cast(@letterCount as varchar(3)) + ' letters in directory: ' + @saveDir

    update @tmpLetterTbl set actualLetters = @letterCount where docID = @I              
    set @I=@I+1

    END

我希望使用stroed proc getDirFileCount返回的目录中的文件数来更新表变量@tmpLetterTbl

我没有错误,但 @letterCount 未填充。

我在这做错了什么?

感谢 菲利普

1 个答案:

答案 0 :(得分:4)

您还必须在对过程的调用中使用OUTPUT修饰参数:

 exec getDirFileCount @SaveDir, @letterCount OUTPUT