2014-06-25 86 views
0

是否有一些方法可以與SQL Server一起使用來創建我可以在基於公式/計算字段的查詢中使用的變量?迄今爲止我看到的例子都只是將變量設置爲字面值。SQL Server - 將公式和/或計算字段設置爲變量?

對於我正在處理的查詢,我需要獲得的一些計算字段基於多個其他計算字段之間的廣泛公式,這些字段通常都會使用類型轉換。當我想要進一步構建時,對於嵌套的IIF語句使用這些不同的計算字段,將其全部寫入該語句中變得非常麻煩。

這將是如此容易得多,看起來那麼如果我可以指更清潔這些計算領域的簡單變量,而不是複製跨越5+線粘貼他們,看起來像一個完整的一塌糊塗

回答

2

一個簡單 - 但醜陋的解決方案是嵌套的select語句:

Select a+(b*c) from (
    select 
     x*y AS a, 
     price/amount AS b, 
     acos(y) AS c 
    from TheTable 
) as q 
+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 
) 

然後你可以使用CT Es表內的值函數。

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'