I am building a dynamic insert statement within a stored procedure.
I build up the sql syntax in a variable and then execute it with EXEC(@VarcharVariable)
.
The SQL insert works fine but when I execute SET @Record_ID = Scope_Identity()
afterwards, I don't get a value.
How can I capture this? Do I need to wrap it into the EXEC
?
Basic example, using sp_executesql
DECLARE @sql NVARCHAR(MAX)
DECLARE @Id INTEGER
SET @sql = 'INSERT MyTable (Field1) VALUES (123); SELECT @Id = SCOPE_IDENTITY()'
EXECUTE sp_executesql @sql, N'@Id INTEGER OUTPUT', @Id OUTPUT
-- @Id now has the ID in
You can try this also.....
CREATE PROCEDURE [dbo].[SaveSingleColumnValueFromGrid]
(
@TableName VARCHAR(200),
@ColumnName VARCHAR (200),
@CompareField VARCHAR(200),
@CompareValue VARCHAR(200),
@NewValue VARCHAR(200),
@Result INT OUTPUT
)
AS
BEGIN
DECLARE @SqlString NVARCHAR(2000),
@id INTEGER = 0;
IF @CompareValue = ''
BEGIN
SET @SqlString = 'INSERT INTO ' + @TableName + ' ( ' + @ColumnName + ' ) VALUES ( ''' + @NewValue + ''' ) ; SELECT @id = SCOPE_IDENTITY()';
EXECUTE sp_executesql @SqlString, N'@id INTEGER OUTPUT', @id OUTPUT
END
ELSE
BEGIN
SET @SqlString = 'UPDATE ' + @TableName + ' SET ' + @ColumnName + ' = ''' + @NewValue + ''' WHERE ' + @CompareField + ' = ''' + @CompareValue + '''';
EXECUTE sp_executesql @SqlString
set @id = @@ROWCOUNT
END
SELECT @Result = @id
END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With