How to look dynamically for a keyword in all columns of a table

后端 未结 1 908
無奈伤痛
無奈伤痛 2021-01-24 00:38

I want to be able to look dynamically for a specific keyword in all columns of a table. The purpose of the script would be to only have to change the keyword and the table name,

相关标签:
1条回答
  • 2021-01-24 01:15

    This is probably what you're after. Note i limit the search to only look in columns that are string types, properly quote your objects (using QUOTENAME) and parametrise the statement:

    DECLARE @Schema sysname,
            @Table sysname,
            @Keyword varchar(100);
    
    DECLARE @SQL nvarchar(MAX);
    SET @Schema = N'dbo';
    SET @Table = N'icp_yyclient';
    SET @Keyword = 'Smith';
    
    SET @SQL = N'SELECT *' + NCHAR(13) + NCHAR(10) + 
               N'FROM ' + QUOTENAME(@Schema) + N'.' + QUOTENAME(@Table) + NCHAR(13) + NCHAR(10) + 
               N'WHERE @Keyword IN (' + STUFF((SELECT N',' + QUOTENAME(C.[name])
                                               FROM sys.columns c
                                                    JOIN sys.tables t ON c.object_id = t.object_id
                                                    JOIN sys.schemas s ON t.schema_id = s.schema_id
                                                    JOIN sys.types ct ON c.system_type_id = ct.system_type_id
                                                WHERE t.[name] = @Table
                                                  AND s.[name] = @Schema
                                                  AND ct.[name] IN (N'varchar',N'char',N'nvarchar',N'nchar',N'sysname')
                                                FOR XML PATH(N''),TYPE).value('.','nvarchar(MAX)'),1,1,N'') + N');';
    PRINT @SQL; --Your best friend
    
    EXEC sp_executesql @SQL, N'@Keyword varchar(100)', @Keyword;
    
    0 讨论(0)
提交回复
热议问题