0

I'm passing a table valued parameter to a stored procedure to use in a where clause, but I want to check whether the parameter has been passed-in or not first. What is the best way to check a parameter of this type? For example, I want the select to be along the lines of:

SELECT * 
FROM tableName
WHERE
@TVP IS NULL OR RecordID IN (SELECT * FROM @TVP)
2
  • 1
    You should take a look at this article on the topic. sqlinthewild.co.za/index.php/2009/09/15/… Commented Aug 19, 2015 at 18:46
  • 2
    The TVP is a table, not a variable. You can't say WHERE dbo.tableName IS NULL so try WHERE NOT EXISTS (SELECT 1 FROM @TVP). Also you should name the column instead of saying *. Commented Aug 19, 2015 at 18:56

1 Answer 1

3

If a parameter of a table valued type is not passed, it will just be an empty table. So you can use:

SELECT * 
FROM tableName
WHERE not exists(select * from @TVP)
    or RecordID IN (SELECT * FROM @TVP)
Sign up to request clarification or add additional context in comments.

2 Comments

Well, I wouldn't recommend bothering with a count, this requires a full scan which can be expensive if the TVP can be large.
Good point... I was just in the middle of editing my answer when your comment popped up. :)

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.