处理动态SQL的NULL值(插入)

时间:2016-09-08 11:39:49

标签: sql-insert

我创建了几个输入参数的存储过程,然后传递给动态SQL命令。当我通过' NULL'对于其中一个输入参数,整个动态SQL语句变为NULL。示例代码为:

DECLARE @FName VARCHAR(10);
DECLARE @MName VARCHAR(10);
DECLARE @LName VARCHAR(10);
DECLARE @InsertSql VARCHAR(MAX);

SET @FName = 'John';
SET @MName = NULL;
SET @LName = 'Williams';

SET @InsertSql = 'INSERT INTO  TestName (TestIDFirstName,TestMiddleName,TestLastName) Values (''' + @FName + ''',''' + @MName + ''',''' + @LName + ''')';

SELECT @InsertSql; --Returns NULL.  

当任何输入参数具有NULL值时,如何处理。我想用一个Insert语句处理这种情况。

3 个答案:

答案 0 :(得分:1)

USE COALESCE

SET @InsertSql = 'INSERT INTO  TestName (TestIDFirstName,TestMiddleName,TestLastName) Values (''' +COALESCE(@FName,'') + ''',''' + COALESCE(@MName,'') + ''',''' + COALESCE(@LName,'') + ''')';

答案 1 :(得分:0)

使用CONCAT有效:

DECLARE @FName VARCHAR(10);
DECLARE @MName VARCHAR(10);
DECLARE @LName VARCHAR(10);
DECLARE @InsertSql VARCHAR(MAX);

SET @FName = 'John';
SET @MName = NULL;
SET @LName = 'Williams';

SET @InsertSql = CONCAT ('INSERT INTO  TestName (TestIDFirstName,TestMiddleName,TestLastName) Values (''', @FName, ''',','''', @MName, ''',''',@LName, ''')')           

SELECT @InsertSql; --Returns NULL.  

答案 2 :(得分:0)

我发现的唯一方法是将insertSQL语句替换为:

SET @InsertSql = 
'INSERT INTO TestName (TestIDFirstName,TestMiddleName,TestLastName) 
 Values
 (''' + @FName + ''','
 + CASE WHEN cast ( @MName as varchar) IS NULL THEN 'NULL' ELSE cast(''''+@MName+'''' as varchar) END
 + ',''' + @LName + ''')';

如果@MName为空,则@InsertSql等于:

INSERT INTO TestName (TestIDFirstName,TestMiddleName,TestLastName)     Values    ('John',NULL,'Williams')

其他

INSERT INTO TestName (TestIDFirstName,TestMiddleName,TestLastName)     Values    ('John','Florian','Williams')