Reputation: 3855
i have the following sql command
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?! );
the userName is a string (NVARCHAR in the sql), sometimes it has a value and sometimes its set to null, so i have 2 cases
username='someUserName'
username=Null
how can i achieve this in the current syntax without if statements or any additional checking
Upvotes: 0
Views: 286
Reputation: 4081
Try something like:
SELECT [file] FROM [ApplicationSettings]
WHERE [id] = @id And username=ISNULL(@username,username)
If @username is NULL, it'll compare username to username which always will be true; and if it is not null, it'll then compare username = @username. You could also use a CASE for comparison, but I find the above syntax more clean myself.
Upvotes: 2