如何在CTE(SQL Server 2005)之后使用if语句

前端之家收集整理的这篇文章主要介绍了如何在CTE(SQL Server 2005)之后使用if语句前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
昨天晚上,我正在写一个这样的简单的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

我发现编译之后,它会抛出错误,如“错误的语句,如果”

哪里不对?

但是,我用另外一种方式做到了.但是我想知道为什么它不起作用!

解决方法

Common table expressions在单个语句的上下文中定义:
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;

A CTE must be followed by a single SELECT,INSERT,UPDATE,MERGE,or DELETE statement that references some or all the CTE columns. A CTE can also be specified in a CREATE VIEW statement as part of the defining SELECT statement of the view

猜你在找的MsSQL相关文章