SQL查询内部连接与临时表

时间:2013-10-13 06:53:40

标签: sql sql-server inner-join common-table-expression

我正在尝试使用此处显示的示例在临时表中设置值:SQL output: Is it possible to create a temporary output column?

我创建了我的初始表,我使用列名来建立新列值“operdesc”的总体数。

这是我的工作表查询,其中我获得了我需要的COLUMN_NAME值。我想添加一个临时列“OPERAND”:

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;

“客户”表是一个视图。

提前多多谢谢!

1 个答案:

答案 0 :(得分: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')