2

Is there any simple function in TSQL that could replace the below tsql?

SELECT * FROM Users
WHERE (Username IS NULL OR Username != @username)

I could write the below but that's not bullet proof due to the hard coded text!

 SELECT * FROM Users
    WHERE ISNULL(Username, 'dummytext') != @username

Thanks,

3
  • 2
    What do you want to replace and why? Commented Dec 7, 2012 at 9:08
  • To use a built-in function if any exists and be shorter. Commented Dec 7, 2012 at 9:15
  • 1
    Your original SQL is short and clear. I see no reason to replace it unless you run into performance problems. In case you do, you should look at Jack Douglas answer, which may be able to utilize an index. Commented Dec 7, 2012 at 9:46

3 Answers 3

3

In this instance I don't think its worth having a UDF to manage this condition.

(Username IS NULL OR Username != @username) is 43 characters long

dbo.IsNullorNotEqual(Username, @Username)=0 is 43 characters long


Sure, you could make the function name slightly shorter, but its not worth breaking convention to make a function call shorter.

Furthermore, not using a UDF in this instance will let you see exactly whats going on.

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

Comments

2

Daniel asked good question...

My 3 cents:

  1. Using function make impossible to use index :(.
  2. However != operator is supported by most databases (based on this answer, <> is ANSI compliant.
  3. You can use COALESCE() instead of ISNULL() but it still function which blocking using index :(.

Comments

2

I'm not certain what you are trying to achieve, but does this help?

SQL Fiddle

Schema Setup:

create table Users(Username varchar(99));
insert into Users(Username) values('Alice');
insert into Users(Username) values('Bob');
insert into Users(Username) values(null);

Query 1:

DECLARE @username varchar(99)
SET @username = 'Alice'
SELECT * FROM Users 
EXCEPT
SELECT * FROM Users where Username = @username

Results:

| USERNAME |
------------
|   (null) |
|      Bob |

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.