在MSSQL中使用LIKE运算符设置SQL查询

时间:2018-06-25 11:57:38

标签: sql-server

我在执行%操作符时出错。你能帮我写正确的方法吗?

SET @sql = N'DELETE TOP(1000) FROM ' + @tableName + ' WHERE ItemId
        in (Select ItemId from dbo.History_Item 
            WHERE (
                [FullyQualifiedName] LIKE ''' + @machine_DS + '.%'''
                OR 
                [FullyQualifiedName] Like '''+ @machine_Kpi + '.%'''
                )
            )
        AND datetime between'''+ @startDate +''' And '''+ @endDate +'''

我点击了此链接 How to parameterize query with like operator in Sql Server

但无法完美设置。我知道它是重复查询,但设置时遇到了麻烦。

2 个答案:

答案 0 :(得分:2)

应该是这样的:

  

NB您是否真的要在您的like运算符中使用。%?

SQL代码

declare @sql nvarchar(max)
declare @tablename nvarchar(max) = 'test'
declare @machine_ds nvarchar(max) ='testmachine'
declare @startdate nvarchar(max) = '2018-06-25'
declare @enddate nvarchar(max) = '2018-06-26'
declare @machine_Kpi nvarchar(max) ='testmachinekpi'

SET @sql = 'DELETE TOP(1000) FROM ' + @tableName + ' WHERE ItemId

 in (Select ItemId from dbo.History_Item 
            WHERE (
                [FullyQualifiedName] LIKE ''' + @machine_DS + '.%''
                OR 
                [FullyQualifiedName] Like '''+ @machine_Kpi + '.%''
                )
            )
        AND datetime between'''+ @startDate +''' And '''+ @endDate +''''

       print @sql

无需注入的SQL代码

declare @sql nvarchar(max)
declare @tablename nvarchar(max) = 'test'
declare @machine_ds nvarchar(max) ='testmachine'
declare @startdate date = '2018-06-25'
declare @enddate date = '2018-06-26'
declare @machine_Kpi nvarchar(max) ='testmachinekpi'

SET @sql = 'DELETE TOP(1000) FROM ' + @tableName + ' WHERE ItemId

 in (Select ItemId from dbo.History_Item 
            WHERE (
                [FullyQualifiedName] LIKE ''' + @machine_DS + '.%''
                OR 
                [FullyQualifiedName] Like '''+ @machine_Kpi + '.%''
                )
            )
        AND datetime between @StartDate And @EndDate'

        exec sp_executesql @SQL,N'@StartDate date, @EndDate date',@StartDate = @startdate,@EndDate = @enddate

SQL输出

DELETE TOP(1000) FROM test WHERE ItemId

 in (Select ItemId from dbo.History_Item 
            WHERE (
                [FullyQualifiedName] LIKE 'testmachine.%'
                OR 
                [FullyQualifiedName] Like 'testmachinekpi.%'
                )
            )
        AND datetime between'2018-06-25' And '2018-06-26'

答案 1 :(得分:1)

只需编辑您的sql脚本

SET @sql = N'DELETE TOP(1000) FROM ' + @tableName + ' WHERE ItemId
        in (Select ItemId from dbo.History_Item 
            WHERE (
                [FullyQualifiedName] LIKE ''' + @machine_DS + '.%''
                OR 
                [FullyQualifiedName] Like '''+ @machine_Kpi + '.%''
                )
            )
        AND datetime between'''+ @startDate +''' And '''+ @endDate +''''