2013-10-13 65 views
3

我想在一個臨時表中設置值的利用這裏顯示的例子:SQL output: Is it possible to create a temporary output column?SQL查詢內部聯接與臨時表

我創建了我最初的表,其中我使用的列名的基礎一列新的「operdesc」值。

這裏是我的工作表查詢,我得到我需要的COLUMN_NAME值。我想補充一個臨時列「操作數」:

SELECT  COLUMN_NAME, DATA_TYPE, 'OPERAND' AS TempField, 
        CASE WHEN COLUMN_NAME = 'Street' THEN '=' WHEN COLUMN_NAME = 'Town' THEN 'CW' END AS OPERAND FROM   INFORMATION_SCHEMA.COLUMNS WHERE (TABLE_SCHEMA = 'dbo') AND (TABLE_NAME = 'Customers') ORDER BY COLUMN_NAME 

不過,我希望把它更進一步,使用一個臨時加入簡化它。我遵循這個例子:SQL output: Is it possible to create a temporary output column?但我掛在我的腳本。這是我有,但它不工作,希望我很接近:

WITH XOperLU (xopername, xoperdesc) 
AS 
(
    SELECT xopername, CAST(xoperdesc AS VARCHAR(20)) 
    FROM (
      VALUES ('Street', 'SS'), 
       ('Town', 'TW')      
     ) AS XOperLU (xopername, xoperdesc) 
) SELECT COLUMN_NAME as T1.COLUMN_NAME, DATA_TYPE as T1.DATA_TYPE, S1.xoperdesc AS Description FROM INFORMATION_SCHEMA.COLUMNS AS T1 WHERE (TABLE_SCHEMA = 'dbo') AND (TABLE_NAME = 'Clients') 
    INNER JOIN XOperLU AS S1 
     ON S1.xopername = T1.COLUMN_NAME; 

'客戶'表是一個視圖。

非常感謝提前!

+0

SQL Server 2008 R2 – ripsin

回答

1

你幾乎沒問題,但你有T1別名用於列別名而不是列,最重要的是你有WHERE之前JOIN。此作品:

WITH XOperLU (xopername, xoperdesc) 
AS 
(
    SELECT xopername, CAST(xoperdesc AS VARCHAR(20)) 
    FROM (
      VALUES ('Street', 'SS'), 
       ('Town', 'TW')      
     ) AS XOperLU (xopername, xoperdesc) 
) SELECT T1.COLUMN_NAME as COLUMN_NAME, T1.DATA_TYPE as DATA_TYPE, S1.xoperdesc AS Description FROM INFORMATION_SCHEMA.COLUMNS AS T1 
    INNER JOIN XOperLU AS S1 
     ON S1.xopername = T1.COLUMN_NAME 
     WHERE (TABLE_SCHEMA = 'dbo') AND (TABLE_NAME = 'Clients') 

如果您希望查看沒有指定說明的所有其他列,請將其設置爲'XX',可以使用左連接:

WITH XOperLU (xopername, xoperdesc) 
AS 
(
    SELECT xopername, CAST(xoperdesc AS VARCHAR(20)) 
    FROM (
      VALUES ('Street', 'SS'), 
       ('Town', 'TW')      
     ) AS XOperLU (xopername, xoperdesc) 
) SELECT T1.COLUMN_NAME as COLUMN_NAME, T1.DATA_TYPE as DATA_TYPE, ISNULL(S1.xoperdesc,'XX') AS Description FROM INFORMATION_SCHEMA.COLUMNS AS T1 
    LEFT JOIN XOperLU AS S1 
     ON S1.xopername = T1.COLUMN_NAME 
     WHERE (TABLE_SCHEMA = 'dbo') AND (TABLE_NAME = 'Clients') 
+0

謝謝!第二組眼睛完美地工作。現在唯一需要的調整是讓我看到原始COLUMN_NAME中的所有記錄,並按照定義(如'Street','SS')在'Description'中設置其餘記錄。這會在'Description'中爲它們創建NULL值。我想定義一個默認值'XX',所以它不會說null。有意義嗎?謝謝! – ripsin

+0

是的,確實如此,祝你好運。 – Szymon

+0

謝謝。有沒有辦法調整它,所以我看到所有記錄(COLUMN_NAMES)的描述設置爲'XX'爲我沒有設置值? – ripsin