Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#中的sql null和null合并运算符_C#_Sql_Sql Server - Fatal编程技术网

c#中的sql null和null合并运算符

c#中的sql null和null合并运算符,c#,sql,sql-server,C#,Sql,Sql Server,我有以下sql命令 var Query = new SqlCommand(@"SELECT [file] FROM [ApplicationSettings] WHERE [id] = @id And username=@username", con); Query.Parameters.AddWithValue("@id", fileName); Query.Parameters.AddWithValue("@username", userName ?? //then what?! ); 用

我有以下sql命令

var Query = new SqlCommand(@"SELECT [file] FROM [ApplicationSettings] WHERE [id] = @id And username=@username", con);
Query.Parameters.AddWithValue("@id", fileName);
Query.Parameters.AddWithValue("@username", userName ?? //then what?! );
用户名是一个字符串(sql中的NVARCHAR),有时有值,有时设置为null, 所以我有两个案子

username='someUserName'
username=Null
在当前语法中,如果没有if语句或任何附加检查,如何实现这一点

SELECT [file] FROM [ApplicationSettings] 
WHERE [id] = @id And username=ISNULL(@username,username)
如果@username为空,它会将username与username进行比较,这将始终为真;如果不为null,则比较username=@username。
您也可以使用CASE进行比较,但我发现上面的语法更清晰。

在添加参数时,您可以尝试类似IsDBNull(userName)?userName:“”的方法。语法不太确定。但是,如果您想知道如何将参数设置为null,请尝试:
command.Parameters.Add(“@parameter”,SqlDbType.VarChar)。Value=parameterValue??DBNull.Value@adrianm请尝试一下,你会发现为什么它不起作用