我搜索了高和低,沒有找到答案。所以我希望你們n個女孩可以在我的路上幫助我:變量在動態SQL中有意外的NULL值
我無法弄清楚爲什麼在「SET @ new_comment ...」中使用它時爲什麼@old_comment是NULL,但是當它返回一個很好的值時使用它在輸出參數「SET @commentOldOUT ...」
CREATE PROCEDURE [dbo].[SP_NY_KOMMENTAR]
@tabel NVARCHAR(100),
@id INT,
@comment NVARCHAR(1000) = NULL,
@commentOldOUT NVARCHAR(1000) = NULL OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @user NVARCHAR(30);
DECLARE @date NVARCHAR(10);
DECLARE @new_id VARCHAR(100);
DECLARE @new_comment NVARCHAR(MAX);
DECLARE @old_comment NVARCHAR(MAX);
DECLARE @old_comm NVARCHAR(MAX);
DECLARE @old NVARCHAR(MAX);
DECLARE @q2 NVARCHAR(MAX);
SET @new_id = (SELECT CAST(@id AS VARCHAR(100)));
SET @user = (SELECT ORIGINAL_LOGIN());
SET @date = (SELECT CONVERT(DATE,GETDATE()));
SET @old = 'SELECT comment FROM '+ @tabel +' WHERE id = ' + @ny_id;
EXEC sp_executesql
@query = @old,
@params = N'@old_comm NVARCHAR(MAX) OUTPUT',
@old_com = @old_comm OUTPUT;
SET @old_comment = (SELECT @old_comm);
SET @commentOldOUT = @old_comment;
SET @new_comment = COALESCE(@old_comment + CHAR(13),'') + '[' + @user + ' ' + @date + '] ' + @comment;
SET @q2 = N'UPDATE ' + @tabel + ' SET comment = ''' + @new_comment + ''' WHERE id = ' + @ny_id;
EXEC (@q2);
END
當調試它時,@old_comment不受'EXEC sp_executesql的分配 @query = @old, @params = N '@ old_comm NVARCHAR(MAX)OUTPUT', @ old_comm = @old_comm OUTPUT; SET @old_comment =(SELECT @old_comm);' –
感謝您提示我調試,我不習慣使用SQL Server和SSMS,我可能會說我不幸更多的是Oracle人員...... –
好的,Oracle也很好。我在學校學習了Oracle,但因爲工作原因,我轉而使用SQL Server。現在,我只做SQL Server。我很高興我的幫助:-) –