我正在嘗試做一些有點奇怪的事情,但無法找出完成它的正確方法。本質上,我試圖提取所有表/視圖和列,其中列名稱就像某個字串。除此之外,我想從該表/視圖和列組合中提取 1 行資料。第二部分是我迷失的地方。我知道我可以使用下面的 select 語句來提取必要的表/視圖和列。
SELECT COLUMN_NAME AS 'ColumnName' ,TABLE_NAME AS 'TableName' FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME LIKE '%email%' ORDER BY TableName,ColumnName;
這樣我就會得到類似下面的東西
|ColumnName |TableName | |emailAddress |all_emails | ....
但我想要得到這樣的東西:
|ColumnName |TableName |Example | |emailAddress |all_emails |[email protected]| ....
有人可以提供任何見解嗎?
P粉3928610472024-02-22 12:09:52
我想不出一種簡單的方法來在查詢中執行此操作,但這裡有一個選項......
將列和表的清單放入臨時表中,並透過循環運行它們,使用動態 SQL 為每個表選擇最大行。
我在下面添加了大量評論來解釋它。
DECLARE @SQL NVARCHAR(1000) DECLARE @TABLE NVARCHAR(1000) DECLARE @COLUMN NVARCHAR(1000) DECLARE @SAMPLE NVARCHAR(1000) DROP TABLE IF EXISTS ##TABLELIST SELECT COLUMN_NAME AS 'ColumnName' ,TABLE_NAME AS 'TableName' ,ROW_NUMBER() OVER (ORDER BY COLUMN_NAME,TABLE_NAME)[RN] INTO ##TABLELIST FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME LIKE '%email%'; ALTER TABLE ##TABLELIST ADD [Sample] NVARCHAR(1000) -- Add a column for your sample row. DECLARE @ROWCOUNTER INT = 1 -- Add a counter for the loop to use. WHILE @ROWCOUNTER <= (SELECT MAX([RN]) FROM ##TABLELIST) -- Keep the loop running until the end of the list. BEGIN UPDATE ##TABLELIST SET @TABLE = TableName WHERE [RN] = @ROWCOUNTER -- Get the table name into a variable. UPDATE ##TABLELIST SET @COLUMN = ColumnName WHERE [RN] = @ROWCOUNTER -- Get the column name into a variable. SET @SQL = 'SELECT @SAMPLE = MAX([' + @COLUMN + ']) FROM [' + @TABLE + ']' -- Create SQL statement to pull max column from table specified in variables. EXEC SP_EXECUTESQL @SQL, N'@SAMPLE NVARCHAR(1000) OUTPUT', @SAMPLE OUTPUT -- Execute SQL and put the output into the @SAMPLE variable. UPDATE ##TABLELIST SET [Sample] = CAST(@SAMPLE AS NVARCHAR(1000)) WHERE [RN] = @ROWCOUNTER -- Insert the SQL output into the sample column. SET @ROWCOUNTER = @ROWCOUNTER+1 -- Add one to the row counter to move to the next column and table. END SELECT * FROM ##TABLELIST -- Select final output.