我正在使用下面的存储过程。对于名为LockedByName
和LockedByLoginName
的参数,我想传递一个字符串(可以包含空格等 - 所以我用单引号引用它)或NULL值。
该过程适用于字符串,但不适用于空值。我假设这是因为它以某种方式无声地失败,因为它不能将NULL值放入引号。
既可以保留引号又可以保留使用空值的方法?
当参数为空字符串时,它同样会失败,也可以使用。
ALTER PROCEDURE [dbo].[ChangeLockFormStatus]
@FormID as int,
@LockedByName as nvarchar(50) = null,
@LockedByLoginName as nvarchar(50) = null,
@TableName as varchar(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @ActualTableName AS varchar(255)
SELECT @ActualTableName = QUOTENAME( TABLE_NAME )
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = @TableName
DECLARE @sql AS NVARCHAR(MAX)
SELECT @sql = 'UPDATE ' + @ActualTableName
+ ' SET LockedByName=''' + @LockedByName + ''','
+ 'LockedByLoginName=''' + @LockedByLoginName
+ ''' WHERE [ID] = ' + CAST(@FormID AS VARCHAR(25)) + ';'
EXEC(@sql)
END
答案 0 :(得分:4)
如果使用sp_executesql
,您可以继续直接使用参数,而不必将它们变成字符串。类似的东西:
ALTER PROCEDURE [dbo].[ChangeLockFormStatus]
@FormID as int,
@LockedByName as nvarchar(50) = null,
@LockedByLoginName as nvarchar(50) = null,
@TableName as varchar(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @ActualTableName AS varchar(255)
SELECT @ActualTableName = QUOTENAME( TABLE_NAME )
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = @TableName
DECLARE @sql AS NVARCHAR(MAX)
SELECT @sql = 'UPDATE ' + @ActualTableName
+ ' SET LockedByName=@LockedByName,'
+ 'LockedByLoginName=@LockedByLoginName'
+ ' WHERE [ID] = @FormID;'
EXEC sp_executesql @sql,
N'@LockedByName nvarchar(50),@LockedByLoginName nvarchar(50),@FormID int',
@LockedByName,@LockedByLoginName,@FormID
END