SQL Server 中的 IF 条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5818788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IF condition in view in SQL Server
提问by Navaneethan
Is it possible to have a if condition in VIEWS
是否可以在 VIEWS 中设置 if 条件
eg
例如
CREATE VIEW
as
DECLARE @Count int
SET @Count=-1
select @Count=EmpID from EmployeeDetails where ID=200
IF @Count=-1
BEGIN
SELECT * FROM TEAM1
END
ELSE
BEGIN
SELECT * FROM TEAM1
END
采纳答案by Fishcake
No I don't believe this is possible.
不,我不相信这是可能的。
You could use a stored procedure instead to achieve this functionality.
您可以改用存储过程来实现此功能。
回答by MartW
You could try something sneaky with a UNION :
你可以用 UNION 尝试一些偷偷摸摸的东西:
SELECT {fieldlist}
FROM Table1
WHERE EXISTS(SELECT EmpID FROM EmployeeDetails WHERE ID = 200)
UNION ALL
SELECT {fieldlist}
FROM Table2
WHERE NOT EXISTS(SELECT EmpID FROM EmployeeDetails WHERE ID = 200)
This method would require both SELECT statements to return the same set of fields, although their sources might be different.
此方法将要求两个 SELECT 语句返回相同的字段集,尽管它们的来源可能不同。
回答by Gabriel Guimar?es
Views only allow select statements as stated in here
视图只允许选择语句,如here所述
if you need to do if on column values you can use a
如果您需要在列值上执行 if 您可以使用
SELECT
CASE WHEN COLUMN1 = 1 THEN COLUMNX ELSE COLUMNY END
FROM TABLE1
if your need exceeds this you should create a select from a table valued function instead of a view.
如果您的需要超出此范围,您应该从表值函数而不是视图中创建一个选择。
What you need is a simple Procedure
你需要的是一个简单的程序
CREATE PROCEDURE DOSOMETHING
(
@ID INT
)
AS
BEGIN
IF @ID > 100
SELECT 1 AS ID,'ME' AS NAME, GETDATE() AS VARIABLEDATECOL, NEWID() AS VARIABLEGUID
ELSE
SELECT 2 AS ID, 'YOU' AS NAME
END
回答by Thaat Dings
simply use a udf (User defined Function) Here you can use IF, ELSE, WHILE etc.
只需使用 udf(用户定义函数)在这里您可以使用 IF、ELSE、WHILE 等。
But when you are manipulating data (INSERT, UPDATE, DELETE) then you have to use Stored Procedures because udf's aren't able to do that
但是当您操作数据(插入、更新、删除)时,您必须使用存储过程,因为 udf 无法做到这一点