我可以在视图 -sqlserver 或 CTE 中使用 DECLARE 吗?

Can i use DECLARE within a view -sqlserver or CTE?

我尝试了各种方法来获取在创建视图时使用动态变量创建的视图。

DECLARE @Test VARCHAR(64)='ABC'; // <==== attempt

SELECT TOP 10
    U.ID
    ,X.NAME AS yyyy
    ,X.E AS zzzz
FROM TABLE_A U
JOIN TABLE_B X ON U.ID=X.ID
WHERE U.STATUS='HELLO'
**AND X.NAME=@Test**
ORDER BY U.ID DESC

即使我尝试使用 CTE,我也会收到错误消息

CREATE VIEW TESTVIEW AS
WITH Tests AS  (DECLARE @Test VARCHAR(64)='ABC')
    SELECT TOP 10
        U.ID
        ,X.NAME AS yyyy
        ,X.E AS zzzz
    FROM TABLE_A U
    JOIN TABLE_B X ON U.ID=X.ID
    WHERE U.STATUS='HELLO'
    **AND X.NAME=Tests**
    ORDER BY U.ID DESC

您不能在视图中声明变量。为什么不创建视图,然后使用 WHERE 子句中的字符串从视图创建 SELECT

CREATE VIEW TESTVIEW AS
    SELECT TOP 10 -- Wouldn't recommend hardcoding this in a view
        U.ID
        ,X.NAME AS yyyy
        ,X.E AS zzzz
        ,X.NAME 
    FROM TABLE_A U
    JOIN TABLE_B X ON U.ID=X.ID
    WHERE U.STATUS='HELLO';

SELECT
   *
FROM TESTVIEW
WHERE NAME = 'ABC';

您可以使用像这样的 CTE 在视图中模拟它:

CREATE VIEW TESTVIEW AS
    
WITH CTE AS (
   SELECT
       'ABC' as var
)

SELECT TOP 10 --Still wouldn't recommend hardcoding this in a view
        U.ID
        ,X.NAME AS yyyy
        ,X.E AS zzzz
        ,X.NAME 
    FROM TABLE_A U
    JOIN TABLE_B X ON U.ID=X.ID
    WHERE U.STATUS='HELLO'
    AND X.NAME = (SELECT var FROM cte);

SELECT * FROM TESTVIEW;