简体   繁体   中英

How to use “*” to accept all possible variables when declaring a multi-value variable

--NEW INFO-- Below is what I was thinking would accomplish what I am shooting for but it returns a syntax error. Any idea how to fix the syntax error?...

 DECLARE @PersonID TABLE(val int) 
 INSERT INTO @PersonID 
 VALUES (*)

--ORIGINAL POST-- I want to declare a SQL variable that can be referenced in many places in a query.

The following is my SQL to declare the variable:

DECLARE @PersonID TABLE(val int) 

INSERT INTO @PersonID 
VALUES (647), (167087)

But sometimes I don't want to limit my query result set to entries connected with a finite number of variable options.
Is there a way to use the "*" character in the SQL above to open up the variable to be anything?

If so, please share.
This would be a great alternative to commenting out my declare statement as well as every reference to the variable throughout the query.

SQL Server

I think you want something like this:

SELECT someColumn
FROM someTable
WHERE @Variable IS NULL OR SomeColumn = @Variable

If you don't pass anything into the variable all rows are returned. If you do pass something into the variable then it limits the results.

A more lengthy method for table variables would be to use a case statement or IF statement.

IF (SELECT COUNT(*) FROM @Variable) > 0
BEGIN
SELECT someColumns
FROM someTable
INNER JOIN @Variable ON
someColumn = val
END

ELSE
BEGIN
SELECT someColumns
FROM someTable
END

Again, for this table variable, if you set it to NULL or don't insert any rows into it, all rows will be returned for the query. If there are values in the variable then the INNER JOIN us used.

Forgive my formatting. I'm on my mobile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM