I'm attempting to get all records from a table where a certain field is not a blank string or null. Due to the way I'm building the queries, ISNULL
and COALESCE
are not options here. Changing the schema of the database is not an option either.
This is the code I'm running to try to retrieve the records.
using System;
using System.Data.SqlClient;
using System.Linq;
using Dapper;
namespace DapperMCVE
{
internal class UserFinder
{
public static void Main(string[] args)
{
using (var connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;Integrated Security=True"))
{
connection.Execute(@"IF NOT EXISTS(SELECT * FROM sys.tables WHERE name = 'Users')
CREATE TABLE Users(NullableUserId varchar(50) NULL) ON [PRIMARY]");
connection.Execute(@"DELETE Users");
connection.Execute(@"INSERT INTO Users(NullableUserId)
VALUES(''), (NULL), ('SteveSmith@fake.com'), ('Morgan@totallyreal.org')");
var parameters = new DynamicParameters();
parameters.Add("UserIdNull", (string)null);
parameters.Add("UserIdBlank", "");
try
{
var users = connection.Query(@"SELECT *
FROM Users
WHERE NullableUserId IS NOT @UserIdNull
AND NullableUserId != @UserIdBlank", parameters);
Console.WriteLine(users.ToList());
}
catch (SqlException e)
{
Console.WriteLine(e);
}
Console.ReadKey();
}
}
}
}
The error thrown is System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near '@UserIdNull'.
My assumption is that the above code should replicate this query:
SELECT *
FROM Users
WHERE NullableUserId IS NOT NULL
AND NullableUserId != ''
but it seems to be doing something closer to
SELECT *
FROM Users
WHERE NullableUserId IS NOT 'NULL'
AND NullableUserId != ''
If I change the query to
SELECT *
FROM Users
WHERE ISNULL(NullableUserId, '') != ISNULL(@UserIdNull, '')
it works fine. Unfortunately, I cannot use ISNULL
in this case.
I've replicated this in SQL Server 2014 and 2016. We're using 2016 in our production environment.
The profiler reports that the following command is being run:
exec sp_executesql N'SELECT *
FROM Users
WHERE NullableUserId IS NOT @UserIdNull
AND NullableUserId != @UserIdBlank',N'@UserIdNull nvarchar(4000),@UserIdBlank nvarchar(4000)',@UserIdNull=NULL,@UserIdBlank=N''
Which makes me suspect this may be an issue with SQL Server itself?
Things I've tried (to no avail):