I have searched high and low, without finding an answer. So I hope that you guys n girls can help me on my way:
I cant figure out why @old_comment is NULL when I use it in "SET @new_comment...", but it returns a fine value when I use it in the outputparameter "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