在存储过程中将特殊字符 [char(11), char(7)] 作为字符串传递

Passing special character [char(11), char(7)] in stored procedure as string

我想在 table 中搜索所有具有特殊字符的记录 - char(11)、char(7) 等

我找到了一个可以帮助我找到它的存储过程。但它不接受输入参数如下:

EXEC sp_FindStringInTable '%'+char(7)+'%', 'CPOA-TALENTLink-Test-Leeds', 'TALENT_Contact_ChangeLog'

错误:

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '+'.

存储过程:

CREATE PROCEDURE dbo.sp_FindStringInTable 
     @stringToFind NVARCHAR(100), 
     @schema SYSNAME, 
     @table SYSNAME
AS
BEGIN TRY
    DECLARE @sqlCommand VARCHAR(MAX) = 'SELECT * FROM [' + @schema + '].[' + @table + '] WHERE ' 

    SELECT @sqlCommand = @sqlCommand + '[' + COLUMN_NAME + '] LIKE ''' + @stringToFind + ''' OR '
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_SCHEMA = @schema
      AND TABLE_NAME = @table 
      AND DATA_TYPE IN ('char','nchar','ntext','nvarchar','text','varchar')

    SET @sqlCommand = LEFT(@sqlCommand, LEN(@sqlCommand) - 3)

    EXEC (@sqlCommand)
   PRINT @sqlCommand
END TRY
BEGIN CATCH 
   PRINT 'There was an error. Check to make sure object exists.'
   PRINT error_message()
END CATCH 

如错误所述,我无法在 table 中搜索特殊字符。

'[' + @schema + ']'' LIKE ''' + @stringToFind + '''' 这样的文字字符串连接是不安全的。 远非如此。我怀疑对您的查询进行参数化会解决这个问题:

CREATE PROCEDURE dbo.sp_FindStringInTable @stringToFind NVARCHAR(100), @schema sysname, @table sysname 
AS

    BEGIN TRY
        DECLARE @sqlCommand varchar(max);
        SET @sqlCommand = N'SELECT *' + NCHAR(10) + --Formatting yoru dynamic SQL is a very good idea
                          N'FROM ' + QUOTENAME(@schema) + N'.' + QUOTENAME(@table) + NCHAR(10) +
                          N'WHERE' +
                          STUFF((SELECT NCHAR(10) + N'  AND ' + QUOTENAME(COLUMN_NAME) + N'LIKE @String'
                                 FROM INFORMATION_SCHEMA.COLUMNS 
                                 WHERE TABLE_SCHEMA = @schema
                                   AND TABLE_NAME = @table 
                                   AND DATA_TYPE IN ('char','nchar','ntext','nvarchar','text','varchar')
                                 FOR XML PATH(N'')),1,6,N'')
        PRINT @sqlCommand; --your best friend
        EXEC sp_executesql @sqlCommand, N'String nvarchar(100)', @String = @stringToFind;

        END TRY

    BEGIN CATCH 
       PRINT 'There was an error. Check to make sure object exists.'
       PRINT error_message()
    END CATCH 

请注意,我尚未测试以上内容。你最好的朋友在那里帮你调试。

在调用过程中,文字或变量以外的表达式不起作用。

将连接分配给变量并将该变量传递给过程。

DECLARE @p varchar(max) = '%' + char(7) + '%';

EXEC sp_FindStringInTable @p, 'CPOA-TALENTLink-Test-Leeds', 'TALENT_Contact_ChangeLog';