2015-04-15 67 views
0

呈現在表我有一個表「ExcelData」象下面這樣:選擇列的值列在SQL

Id [Title 1] [Title 2] [Address 1] [Address 2] City State 
1  A1   A2   add1   add2   X  Y 
2  B1   B2   add1   add2   X  Y 

我需要以字符串形式查詢該檢查每一列後得到的結果從上面的表格如果它存在於表中或不存在。

Declare @strSQL nvarchar(max), @RecId int 
set @RecId = 1 

--- while循環將用於@Count變量。我的查詢是:

set @strSQL = 'SELECT CASE WHEN EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='ExcelData' and COLUMN_NAME='[Title ' + CONVERT(nvarchar(10), @Count)) THEN(SELECT '[Title ' + CONVERT(nvarchar(10), @Count)]' 
FROM ExcelData where ExcelData.Id = '+ @RecId +') ELSE NULL END AS [Title] 
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='ExcelData' and COLUMN_NAME='[Email]' THEN(SELECT '[Email]' FROM ExcelData where ExcelData.Id = '+ @RecId +') ELSE NULL END AS [Email])' 

Execute(@strSQL) 

我需要的,如果列在表中存在,那麼該列的值結果,如果它不是,那麼查詢應在列值像下面返回null:

所需的結果:

[Title 1] [Title 2] [Email] 
    A1  A2  NULL 

但我沒有得到預期的結果。

回答

1

這應該可以動態獲得[標題1],[標題2],[電子郵件]列的值(如果它們存在),並在@RecId上有一個循環。如果你可以有多個標題/地址欄,你也應該實現這個@Count變量。

DECLARE @strSQL nvarchar(max), 
     @RecId int 

SET @RecId = 1 

WHILE EXISTS (SELECT TOP 1 1 FROM ExcelData WHERE Id = @RecId) 
BEGIN 
    SET @strSQL = ' 
    SELECT '+ 
     (case when exists (select * 
          from INFORMATION_SCHEMA.COLUMNS 
          where table_name = 'ExcelData' and 
           column_name = 'Title 1' 
         ) 
       then '[Title 1]' 
       else 'NULL AS [Title 1]' 
     end) + ', ' + 
     (case when exists (select * 
          from INFORMATION_SCHEMA.COLUMNS 
          where table_name = 'ExcelData' and 
           column_name = 'Title 2' 
         ) 
       then '[Title 2]' 
       else 'NULL AS [Title 2]' 
     end) + ', ' + 
     (case when exists (select * 
          from INFORMATION_SCHEMA.COLUMNS 
          where table_name = 'ExcelData' and 
           column_name = 'Email' 
         ) 
       then '[Email]' 
       else 'NULL AS Email' 
     end) + ' 
    FROM ExcelData 
    WHERE Id = ' + CAST(@RecId AS varchar(50)) 

    EXEC sp_executesql @strSQL 

    SET @RecId = @RecId + 1 
END 

導致:

Title 1 Title 2 Email 
A1  A2  NULL 

Title 1 Title 2 Email 
B1  B2  NULL