system_user 运行 是否在 SQL 语句中多次?

Does system_user run multiple times inside of a SQL statement?

我有许多使用网络内部系统功能的查询。这只是一个非常基本的表示。系统函数的一些实际位置在存储过程、视图和触发器中,一些在简单查询中,而另一些在相当复杂的查询中。我们此时正在进行完整的系统审查,并向我提出了这种情况:

SELECT TOP(100) p.Id, p.Name,
     CASE WHERE SYSTEM_USER = 'ME' THEN 'It is Me.' ELSE 'It is not Me.' END as IsItMe
FROM dbo.Person p
WHERE 1 = 1

如果我返回 100 条记录,至少根据 TOP(100),CASE 语句会 运行 100 次还是查询分析器只 运行 一次,因为它返回的每条记录的结果是否相同?

仅供参考...我们是 运行 SQL Server 2014 以防版本之间存在任何差异。

这取决于功能。

SYSTEM_USER 的这种特定情况下,整个表达式 CASE WHEN SYSTEM_USER = 'ME' THEN 'It is Me.' ELSE 'It is not Me.' END as IsItMe 被评估为 runtime constant

你可以从

看到这个
DECLARE @T TABLE(X INT)

SELECT TOP(100)  CASE WHEN SYSTEM_USER = 'ME' THEN 'It is Me.' ELSE 'It is not Me.' END as IsItMe
FROM @T
OPTION (RECOMPILE
, QUERYTRACEON 3604
, QUERYTRACEON 8605 
, QUERYTRACEON 8606
)

初始树是

LogOp_Top NoTies

    LogOp_Project COL: Expr1003 

        LogOp_Get TBL: @T @T TableID=-1530594778 TableReferenceID=0 IsRow: COL: IsBaseRow1001 Hints( NOLOCK )

        AncOp_PrjList 

            AncOp_PrjEl COL: Expr1003 

                ScaOp_IIF varchar collate 872468488,Var,Trim,ML=13

                    ScaOp_Comp x_cmpEq

                        ScaOp_Intrinsic suser_sname

                            ScaOp_Const TI(varbinary,Var,Trim,ML=1) XVAR(varbinary,Not Owned,Value=EMPTY)

                        ScaOp_Const TI(nvarchar collate 872468488,Var,Trim,ML=4) XVAR(nvarchar,Owned,Value=Len,Data = (4,7769))

                    ScaOp_Const TI(varchar collate 872468488,Var,Trim,ML=9) XVAR(varchar,Not Owned,Value=Len,Data = (9,It is Me.))

                    ScaOp_Const TI(varchar collate 872468488,Var,Trim,ML=13) XVAR(varchar,Not Owned,Value=Len,Data = (13,It is not Me.))

    ScaOp_Const TI(bigint,Null,ML=8) XVAR(bigint,Not Owned,Value=100)

    ScaOp_Const TI(bigint,ML=8) XVAR(bigint,Not Owned,Value=0)

早期转换为

*** Input Tree: ***
        LogOp_Top NoTies

            LogOp_Project COL: Expr1003 

                LogOp_Get TBL: @T @T TableID=-1530594778 TableReferenceID=0 IsRow: COL: IsBaseRow1001 Hints( NOLOCK )

                AncOp_PrjList 

                    AncOp_PrjEl COL: Expr1003 

                        ScaOp_Identifier COL: ConstExpr1004 

            ScaOp_Const TI(bigint,Null,ML=8) XVAR(bigint,Not Owned,Value=100)

            ScaOp_Const TI(bigint,ML=8) XVAR(bigint,Not Owned,Value=0)

使用 Expr1003 引用常量表达式