3

我正在尝试使用此处显示的示例在临时表中设置值: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 输出:是否可以创建一个临时输出列?但我挂断了我的剧本。这就是我所拥有的,但它不起作用,希望我很接近:

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;

“客户”表是一个视图。

非常感谢提前!

4

1 回答 1

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')
于 2013-10-13T08:10:58.817 回答