【发布时间】:2014-01-09 20:21:07
【问题描述】:
我有以下代码,它正在检查物理文件计数以确认先前的进程已生成正确数量的文件(在不同的文件夹中)
set NOCOUNT ON
declare @DateOffset int
set @DateOffset=0
-- Create a table variable to store user data
DECLARE @myTable TABLE
(
docID INT IDENTITY(1,1),
docRef VARCHAR(10),
YPTMPID varchar(3),
saveDir VARCHAR(500),
totalLettersExpected int,
actualLetters int
);
insert @myTable SELECT docRef, YPTMPID,
saveDir=max(Save_Directory) + cast(YEAR(GETDATE()-@DateOffset) as varchar(4)) + '\' + datename(month, GETDATE()-@DateOffset) + '\'+SUBSTRING(CONVERT(CHAR(20), GETDATE()-@DateOffset, 101),4, 2) + '.' + LEFT(CONVERT(CHAR(20), GETDATE()-@DateOffset, 101), 2)
+ '.' + SUBSTRING(CONVERT(CHAR(20), GETDATE()-@DateOffset, 101),7, 4),
COUNT(*) as 'Total Letters', null
FROM [alpsMaster].[dbo].[uExtractMonitor]
group by docRef, YPTMPID
order by 1,2
-- Get the number of rows in the looping table
DECLARE @RowCount INT, @SQL nvarchar(4000), @LoopSQL nvarchar(4000), @Date varchar(20)
set @Date=rtrim(CONVERT( CHAR(12), getDate()-@DateOffset, 106)) --'29 Oct 2013'
SET @RowCount = (SELECT COUNT(docID) FROM @myTable)
-- Declare an iterator
DECLARE @I INT
-- Initialize the iterator
SET @I = 1
-- Loop through the rows of table @myTable, and for each docRef, check the file directory for the correct number of files
WHILE (@I <= @RowCount)
BEGIN
DECLARE @docRef VARCHAR(10), @saveDir VARCHAR(500), @TemplateID varchar(3), @letterCount int
DECLARE @statement nvarchar(200), @EQRecordCout int
-- Get the data from table and set to variables
SELECT @docRef = docref FROM @myTable WHERE docID = @I
SELECT @saveDir = saveDir FROM @myTable WHERE docID = @I
SELECT @TemplateID = YPTMPID FROM @myTable WHERE docID = @I
update @myTable set actualLetters = 0 where docRef=@docRef
create table #files (subdirectory varchar(100), depth int, [file] int)
insert into #files EXEC master.sys.xp_dirtree @saveDir,0,1;
-- *** PROBLEM HERE ***
set @statement= 'SELECT count(*) FROM BOCTEST.S653C36C.LIVEBOC_A.' + @docRef
print @statement
exec @EQRecordCout=sp_executesql @statement
print @EQRecordCout
select @letterCount = COUNT(*) from #files
print cast(@letterCount as char(3)) + ' files for ' + @docRef
drop table #files
update @myTable set actualLetters = @letterCount where docRef=@docRef-- and YPTMPID=@TemplateID
-- Increment the iterator
SET @I = @I + 1
END
select * from @myTable
set NOCOUNT OFF
在我的最终WHILE LOOP 中,我想使用动态 SQL 获取 iSeries 远程服务器上每个文件中的记录计数(SQL 字符串末尾的表名 docRef 是动态的)
但即使它执行得很好,我进入变量 @EQRecordCout 的所有内容都是零。这是不正确的,虽然有些表是空的,但大部分都有记录
返回值的正确写法是什么?
set @statement= 'SELECT count(*) FROM BOCTEST.S653C36C.LIVEBOC_A.' + @docRef
print @statement
exec @EQRecordCout=sp_executesql @statement
print @EQRecordCout
谢谢 菲利普
【问题讨论】:
标签: sql tsql dynamic-sql remote-server