昨晚我在写一个简单的T-SQL程序,像这样
DECLARE @ROLEID AS INT SELECT @ROLEID = [ROLE ID] FROM TBLROLE ;WITH CTE AS ( SELECT * FROM SOMETABLE ) IF (@ROLEID = 1) BEGIN //SOMECODE END ELSE IF(@ROLEID = 2) BEGIN //SOMECODE END ELSE BEGIN //SOMECODE END
编译后我发现它抛出错误,例如“ if附近的语句不正确”
怎么了?
但是,我通过其他方式做到了这一点。但是我想知道为什么它不起作用!
公用表表达式是在单个语句的上下文中定义的:
WITH cte_name AS ( <cte definition>) <statement that uses cte>;
因此,您可以执行以下操作:
WITH CTE AS ( SELECT * FROM SOMETABLE ) SELECT * FROM CTE;
或者
WITH CTE AS ( SELECT * FROM SOMETABLE ) UPDATE CTE SET somefield = somevalue WHERE id = somekey;
CTE之后必须是引用某些或所有CTE列的单个SELECT,INSERT,UPDATE,MERGE或DELETE语句。也可以在CREATE VIEW语句中指定CTE作为视图的定义SELECT语句的一部分