搜索

首页  >  问答  >  正文

根据列名从多个表返回数据的SQL方法

我正在尝试做一些有点奇怪的事情,但无法找出完成它的正确方法。本质上,我试图提取所有表/视图和列,其中列名称就像某个字符串。除此之外,我想从该表/视图和列组合中提取 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粉904450959P粉904450959277 天前448

全部回复(1)我来回复

  • P粉392861047

    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.
    
    

    回复
    0
  • 取消回复