我创建了一个用户定义的标量函数,其输入参数是用于评估和返回值的字符串 - 0 或 1(假或真)。现在,我可以做愿望交叉应用......
以下是示例:
SELECT [dbo].[fn_XxCustom_EvaluateExpression] ('0') -- 0
SELECT [dbo].[fn_XxCustom_EvaluateExpression] ('1') -- 1
SELECT [dbo].[fn_XxCustom_EvaluateExpression] ('1*1') -- 1
SELECT [dbo].[fn_XxCustom_EvaluateExpression] ('1+1') -- 1
SELECT [dbo].[fn_XxCustom_EvaluateExpression] ('1*0') -- 0
SELECT [dbo].[fn_XxCustom_EvaluateExpression] ('0+1*0*1+0*1+0') -- 0
SELECT [dbo].[fn_XxCustom_EvaluateExpression] ('1+1+0+1*0*1+1*1+0') -- 1
我相信有更好的方法可以做到这一点,也许使用反向波兰表示法和递归 CTE,但没有时间尝试。无论如何,如果有人需要做类似的事情,这是源代码:
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_XxCustom_EvaluateExpression]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
DROP FUNCTION [dbo].[fn_XxCustom_EvaluateExpression]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[fn_XxCustom_EvaluateExpression]
(
@Expression NVARCHAR(MAX)
)
RETURNS TINYINT
AS
BEGIN
DECLARE @ExpressionValue TINYINT = 0
IF LEN(@Expression) > 0 AND @Expression IS NOT NULL
BEGIN
-- Checking if this is expression
IF CHARINDEX('+', @Expression) = 0 AND CHARINDEX('*', @Expression) = 0
BEGIN
SET @ExpressionValue = CAST(@Expression AS TINYINT)
END
ELSE
BEGIN
-- Checking if the expression is computed (contains both '*' and '+')
IF CHARINDEX('+', @Expression) > 0 AND CHARINDEX('*', @Expression) > 0
BEGIN
DECLARE @ExpressionsTable TABLE
(
ExpressionID INT IDENTITY(1,1)
,Expression NVARCHAR(MAX)
,ExpressionValue TINYINT
)
DECLARE @XML XML = N'<r><![CDATA[' + REPLACE(@Expression, '+', ']]></r><r><![CDATA[') + ']]></r>'
-- Populate the table with simple expressions (expression which only contains '+' or '*' is simple)
INSERT INTO @ExpressionsTable (Expression)
SELECT DISTINCT RTRIM(LTRIM(T.c.value('.', 'nvarchar(250)')))
FROM @xml.nodes('//r') T(c)
-- Creating a simple expressions with result values
UPDATE @ExpressionsTable
SET ExpressionValue = IIF(CHARINDEX('+', Expression) = 0 AND CHARINDEX('*', Expression) = 0 , Expression, IIF(CHARINDEX('+', Expression) > 0,IIF(CHARINDEX('1', Expression) > 0, 1, 0),IIF(CHARINDEX('0', Expression) > 0, 0, 1)))
-- Evaluating the final expression
SET @ExpressionValue = IIF(CHARINDEX('1', SUBSTRING((SELECT '+' + CAST(ExpressionValue AS VARCHAR(1)) FROM @ExpressionsTable FOR XML PATH('')),2,4000)) > 0, 1, 0)
END
ELSE
-- Checking the type of the simple expression (does it contains '+' or '*')
BEGIN
SET @ExpressionValue = IIF(CHARINDEX('+', @Expression) > 0,IIF(CHARINDEX('1', @Expression) > 0, 1, 0),IIF(CHARINDEX('0', @Expression) > 0, 0, 1))
END
END
END
RETURN @ExpressionValue
END
GO