我可以使用一些方法与SQL Server一起创建我可以在基于公式/计算字段的查询中使用的变量吗?到目前为止,我所看到的例子都只涉及将变量设置为文字值。
对于我正在处理的查询,我需要获得的一些计算字段基于多个其他计算字段之间的广泛公式,通常在整个过程中使用类型转换。当我想进一步构建时,使用这些嵌套的IIF语句的所有这些不同的计算字段,它们开始变得非常麻烦,将它们全部写在该语句中。
如果我可以将这些计算字段称为简单变量而不是将它们复制粘贴在5行以上并且看起来像一个完整的混乱
那么它会变得如此简单并且看起来更加清晰答案 0 :(得分:3)
您可以创建一个像这样的表值函数:
CREATE FUNCTION [dbo].[tfu_RPT_SEL_Benutzer]
(
@in_mandant varchar(3)
,@in_sprache varchar(2)
,@in_show_alle bit = 1
)
RETURNS TABLE
AS
RETURN
(
SELECT
BE_ID AS RPT_ID
,@in_mandant AS RPT_MDT_ID
,BE_Vorname AS RPT_Vorname
,BE_Name AS RPT_Nachname
,BE_User AS RPT_User
,
CASE
WHEN LEN(ISNULL(BE_Vorname + ' ', '') + ISNULL(BE_Name, '') ) > 0
THEN ISNULL(BE_Vorname + ' ', '') + ISNULL(BE_Name, '')
ELSE BE_User
END AS RPT_Name
,0 AS RPT_Sort
FROM T_Benutzer
UNION
SELECT
0 AS RPT_ID
,@in_mandant AS RPT_MDT_ID
,'' AS RPT_Vorname
,'' AS RPT_Nachname
,
(
SELECT TOP(1)
CASE UPPER(@in_sprache)
WHEN 'FR' THEN T_RPT_Translations.RTR_Kurz_FR
WHEN 'IT' THEN T_RPT_Translations.RTR_Kurz_IT
WHEN 'EN' THEN T_RPT_Translations.RTR_Kurz_EN
ELSE T_RPT_Translations.RTR_Kurz_DE
END AS RTR_Kurz
FROM T_RPT_Translations
WHERE (RTR_Status = 1)
AND (RTR_MDT_ID = 0)
AND (RTR_ReportName = 'All')
--AND (RTR_IsFlag = 1)
AND (RTR_ItemCaption = 'NA')
--AND (RTR_Code = 1)
) AS RPT_User
,
(
SELECT TOP(1)
CASE UPPER(@in_sprache)
WHEN 'FR' THEN T_RPT_Translations.RTR_Lang_FR
WHEN 'IT' THEN T_RPT_Translations.RTR_Lang_IT
WHEN 'EN' THEN T_RPT_Translations.RTR_Lang_EN
ELSE T_RPT_Translations.RTR_Lang_DE
END AS RTR_Lang
FROM T_RPT_Translations
WHERE (RTR_Status = 1)
AND (RTR_MDT_ID = 0)
AND (RTR_ReportName = 'All')
--AND (RTR_IsFlag = 1)
AND (RTR_ItemCaption = 'NA')
--AND (RTR_Code = 1)
) AS RPT_Name
,999999999 AS RPT_Sort
WHERE @in_show_alle = 1
)
然后你可以在表值函数内使用CTE。
DECLARE @i integer
SET @i=5
;WITH CTE AS (
SELECT
BE_ID
,BE_ID * @i as idmul
FROM T_Benutzer
)
SELECT * FROM CTE
WHERE idmul > 62000
从函数
查询DECLARE @in_mandant varchar(3)
,@in_sprache varchar(2)
,@in_show_alle bit = 1
SET @in_mandant = '0'
SET @in_sprache = 'DE'
SET @in_show_alle = 'true'
SELECT *
FROM tfu_RPT_SEL_Benutzer( @in_mandant, @in_sprache, @in_show_alle )
WHERE RPT_User = 'N/A'
答案 1 :(得分:2)
一个简单但丑陋的解决方案是使用嵌套的select语句:
Select a+(b*c) from (
select
x*y AS a,
price/amount AS b,
acos(y) AS c
from TheTable
) as q