我有下面的代碼,我想循環遍歷一個表並設置一個變量,然後可以用來更新另一個表中的字段,但是當我嘗試讀取時,變量始終顯示爲NULL它。我究竟做錯了什麼?在TSQL中傳遞一個變量
declare @CustId nchar(15)
declare @CustID1 nchar(255)
declare @DateTime1 nchar(25)
declare @finalnote varchar(max)
declare @RowNum int
declare CustList cursor for
select
DateTime, Username, Notes
from tbl_DesignNotes
where OrderNumber = 10645
order by ID
OPEN CustList
FETCH NEXT FROM CustList INTO @DateTime1, @CustId, @CustID1
set @RowNum = 0
WHILE @@FETCH_STATUS = 0
BEGIN
set @RowNum = @RowNum + 1
set @finalnote = @finalnote + ' ' + @DateTime1 + ' ' + @CustId + ' ' + @CustID1;
--select @finalnote
--print @finalnote
select @finalnote as varText;
--print @DateTime1 + ' ' + @CustId + ' ' + @CustID1
FETCH NEXT FROM CustList INTO @DateTime1, @CustId, @CustID1
END
CLOSE CustList
DEALLOCATE CustList
有一個機會,\ @ DateTime1或\ @CustId或\ @ CustID1是空,因此嘗試使用ISNULL(\ @ DateTime1,GETDATE( ))等等。 –
我認爲你可以把你的代碼改寫成單個語句,更新批量 –
看看[這裏](http://stackoverflow.com/questions/194852/concatenate-many-rows-into-a-單個文本字符串),用於從多行數據構建字符串而不使用[RBAR]的一些方法(https://www.simple-talk.com/sql/t-sql-programming/rbar-row- by-agonizing-row /)循環。 – HABO