我有下面的代码,我想循环遍历一个表并设置一个变量,然后可以用来更新另一个表中的字段,但是当我尝试读取时,变量始终显示为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