SQL Server – WHERE NAME LIKE ( A SET OF NAMES )

selectsql serversql server 2014sql-server-2008-r2sql-server-2012

I would like to drop all the jobs related to a set of specific databases.

So I have added all the names into a table variable and I was trying to generate the scripts to drop the jobs.

how can I achieve this?

use msdb
go


DECLARE @R TABLE ( NAME VARCHAR(108) NOT NULL PRIMARY KEY CLUSTERED)

INSERT INTO @R(NAME)
SELECT 
'UK15SUMMProduct' UNION ALL SELECT 
'US15SUMMProduct' UNION ALL SELECT 
'DE15SUMMProduct' UNION ALL SELECT 
'AT15SUMMProduct' UNION ALL SELECT 
'FR15SUMMProduct' UNION ALL SELECT 
'EU15SUMMProduct' UNION ALL SELECT 
'AU15SUMMProduct' UNION ALL SELECT 
'UK15SUMSProduct' UNION ALL SELECT 
'US15SUMSProduct' UNION ALL SELECT 
'DE15SUMSProduct' UNION ALL SELECT 
'AT15SUMSProduct' UNION ALL SELECT 
'FR15SUMSProduct' UNION ALL SELECT 
'EU15SUMSProduct' UNION ALL SELECT 
'AU15SUMSProduct'


SELECT S.* 
FROM SYSJOBS S
WHERE NAME LIKE ( SELECT NAME FROM  @R)

something like the select above, I want to see all the jobs that have the database names in them and delete them, for example, like in the script below:

exec sp_delete_job @job_name = 'WebFeed UK15SUMMProduct', @delete_unused_schedule = 0

Best Answer

Here is the whole query:

Declare @job sysname
Declare jobs_cursor Cursor For
    Select S.name 
    From msdb.dbo.SYSJOBS S
    Inner Join (values
        ('UK15SUMMProduct')
        , ('US15SUMMProduct') 
        , ('DE15SUMMProduct') 
        , ('AT15SUMMProduct') 
        , ('FR15SUMMProduct') 
        , ('EU15SUMMProduct') 
        , ('AU15SUMMProduct') 
        , ('UK15SUMSProduct') 
        , ('US15SUMSProduct') 
        , ('DE15SUMSProduct') 
        , ('AT15SUMSProduct') 
        , ('FR15SUMSProduct') 
        , ('EU15SUMSProduct') 
        , ('AU15SUMSProduct')
    ) as n(name) on S.name like '%'+n.name + '%'

Open jobs_cursor
Fetch Next From jobs_cursor into @job

While @@Fetch_Status = 0
Begin
    Print 'Remove: '+@job
    exec sp_delete_job @job_name = @job, @delete_unused_schedule = 0
    Fetch Next From jobs_cursor into @job
End

Close jobs_cursor
Deallocate jobs_cursor

Part of it is similar to previous answers.

You can replace values(...) by a table variable or a real table.