0

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

3
  • you can try something like IsDBNull(userName)?UserName:"" while adding the parameter. not sure with syntax. but its a try Commented Dec 7, 2013 at 18:57
  • If you want to know how to set a parameter to null: command.Parameters.Add("@Parameter", SqlDbType.VarChar).Value = parameterValue ?? DBNull.Value; Commented Dec 8, 2013 at 11:03
  • @adrianm please try it and you will find out why it wont work Commented Dec 8, 2013 at 11:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.