Using LIKE and % in a stored procedure with parameter in FROM clause

前端 未结 1 1075
夕颜
夕颜 2021-01-27 04:48

I am creating a web page to host a database.

I want this web page to have a search box feature that can update a GridView in visual studio 2017 for tables in SSMS 2014.<

相关标签:
1条回答
  • 2021-01-27 05:12

    Here's a parameterized dynamic SQL example, using QUOTENAME for identifiers:

    CREATE PROCEDURE dbo.Search
        @tableName sysname,
        @columnSpecifier sysname,
        @searchString nvarchar(50)
    AS
    DECLARE @SQL nvarchar(MAX);
    SET @SQL = N'SELECT * FROM ' + QUOTENAME(@tableName) + N' WHERE ' + QUOTENAME(@columnSpecifier) + N' LIKE @searchString + ''%'';';
    EXEC sp_executesql
          @SQL
        , N'@searchString nvarchar(50)'
        , @searchString = @searchString;
    GO
    

    I suggest one generally avoid AddWithValue because it infers the SQL database type from the provided .NET type. Although this isn't a concern here because you are using a stored procedure and System.String maps to SQL Server nvarchar, it is best to specify the desired SqlDbType and length (or precision and scale) explicitly. Below is one method to do that.

    searchAdapter.SelectCommand.Parameters.Add("@TableName", SqlDbType.NVarChar, 128).Value = TableSearchBox.Text.Trim());   // passing text in first text box in
    searchAdapter.SelectCommand.Parameters.Add("@columnSpecifier", SqlDbType.NVarChar, 128).Value = ColumnSearchBox.Text.Trim());   // passing text in second text box in
    searchAdapter.SelectCommand.Parameters.Add("@searchString", SqlDbType.NVarChar, 50).Value = searchStringBox.Text.Trim());   // passing text in third text box in
    
    0 讨论(0)
提交回复
热议问题