Cannot drop table from within SQL Job, BUT same user using SSMS does not get error

gsaunders 96 Reputation points
2022-09-16T13:54:24.853+00:00

Microsoft SQL Server 2017 (RTM-CU30) (KB5013756) - 14.0.3451.2 (X64)
Jun 22 2022 18:20:15
Copyright (C) 2017 Microsoft Corporation
Standard Edition (64-bit) on Windows Server 2012 R2 Standard 6.3 <X64> (Build 9600: ) (Hypervisor)

We have a SQL Job that has been working without issue until CU30.

We have following command in the script:

if exists(select name from sysobjects where name='table1')  
begin  
 drop table [dbo].[table1]  
end  

The SQL History Log shows the following error:
Executed as user: domain\user1. Cannot drop the table 'table1', because it does not exist or you do not have permission.

The owner of the job is sa and it seems to be running under my user which is fine. I have confirmed Server Roles as public and sysadmin.
The user also has user mapping to the database as db_owner, public and another role required for a specific application.

Nothing has changed here, but after that last CU30 this started happening and makes no sense.

Logged in as that user on SSMS the exact same commands from that SQL Job step it runs without issue.

Is this some sort of bug introduced in CU30?

Thanks in advance for your feedback!

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,667 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,624 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Tom Phillips 17,731 Reputation points
    2022-09-16T15:23:03.483+00:00

    Your query returns all objects. "table1" may not be a table or in the dbo schema.

    The simplest way to do this is to run:

    drop table if exists [dbo].[table1];  
    

  2. Erland Sommarskog 110.2K Reputation points
    2022-09-16T21:27:45.48+00:00

    I agree with Tom. There is all reason to modernise this. sysobjects have been deprecated since 2005.

    At the time the query runs, Table1 may not be a table. Or there may be an object in a different schema with the same name,

    Change it to

    DROP TABLE IF EXISTS dbo.table1

    and be done with it.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.