SQL: Return Column names where column contains a given Value

后端 未结 2 720
无人及你
无人及你 2021-01-17 03:52

i was wondering if there was a command/stored proc i can run in SQL Server that will give me the names of columns that contain given data within a table.

So if i was

2条回答
  •  一整个雨季
    2021-01-17 04:06

    -- input parameters (guessing on type for @value):
    
    DECLARE 
      @schema SYSNAME = N'dbo', 
      @table  SYSNAME = N'z', 
      @value  VARCHAR(64) = '75';
    
    
    -- now, inside the procedure body:
    
    DECLARE @sql NVARCHAR(MAX) = N'SELECT ''cols:'' + STUFF(''''';
    
    SELECT @sql += N' 
      + CASE WHEN EXISTS (SELECT 1 FROM ' 
      + QUOTENAME(@schema) + '.' + QUOTENAME(@table)
      + ' WHERE TRY_CONVERT(VARCHAR(64), ' + QUOTENAME(c.name) 
      + ') = @value) THEN '', ' + c.name + ''' ELSE '''' END'
    FROM sys.tables AS t
    INNER JOIN sys.columns AS c
    ON t.[object_id] = c.[object_id]
    INNER JOIN sys.schemas AS s
    ON t.[schema_id] = s.[schema_id]
    WHERE t.name = @table AND s.name = @schema;
    
    SET @sql += N', 1, 1, '''');'
    
    PRINT @sql;
    
    --EXEC sp_executesql @sql, N'@value VARCHAR(64)', @value;
    

    When you are happy with the output, uncomment the EXEC.

    So let's consider a simple table:

    CREATE TABLE dbo.floob
    (
      a INT, 
      b VARCHAR(32), 
      c VARBINARY(22), 
      d DATE, 
      e DATETIME, 
      f ROWVERSION
    );
    
    INSERT dbo.floob(a,b,c,d,e) VALUES
    ( 75, 'foo', 0x00, GETDATE(), GETDATE()),
    ( 21, '75',  0x00, GETDATE(), GETDATE());
    

    Now, a stored procedure based on the above code:

    CREATE PROCEDURE dbo.FindStringInAnyColumn
      @schema SYSNAME = N'dbo', 
      @table  SYSNAME,
      @value  VARCHAR(64)
    AS
    BEGIN
      SET NOCOUNT ON;
    
      DECLARE @sql NVARCHAR(MAX) = N'SELECT ''cols:'' + STUFF(''''';
    
      SELECT @sql += N' 
        + CASE WHEN EXISTS (SELECT 1 FROM ' 
        + QUOTENAME(@schema) + '.' + QUOTENAME(@table)
        + ' WHERE TRY_CONVERT(VARCHAR(64), ' + QUOTENAME(c.name) 
        + ') = @value) THEN '', ' + c.name + ''' ELSE '''' END'
      FROM sys.tables AS t
      INNER JOIN sys.columns AS c
      ON t.[object_id] = c.[object_id]
      INNER JOIN sys.schemas AS s
      ON t.[schema_id] = s.[schema_id]
      WHERE t.name = @table AND s.name = @schema;
    
      SET @sql += N', 1, 1, '''');'
    
      EXEC sp_executesql @sql, N'@value VARCHAR(64)', @value;
    END
    GO
    

    Sample usage:

    EXEC dbo.FindStringInAnyColumn @table = N'floob', @value = '75';
    

    Output:

    Cols: a, b
    

提交回复
热议问题