简体   繁体   English

声明多值变量时如何使用“ *”接受所有可能的变量

[英]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. --NEW INFO--以下是我在想实现的目标,但返回语法错误。 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. --ORIGINAL POST--我想声明一个SQL变量,该变量可以在查询中的许多地方引用。

The following is my SQL to declare the variable: 以下是我的SQL声明变量:

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? 有没有一种方法可以在上面的SQL中使用"*"字符将变量打开为任意值?

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 SQL服务器

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. 表变量的一种更冗长的方法是使用case语句或IF语句。

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. 同样,对于此表变量,如果将其设置为NULL或不向其中插入任何行,则将为查询返回所有行。 If there are values in the variable then the INNER JOIN us used. 如果变量中有值,则使用INNER JOIN。

Forgive my formatting. 原谅我的格式。 I'm on my mobile. 我在用手机。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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