简体   繁体   中英

Primary Key Violation and SQL Server Job Agent

So I have a SQL Server job that runs every night that truncates a table and runs a query that pivots a count of data into columns from another table and inserts said results into that truncated table.

I have gone through quite a few different iterations of this job already and this is what I've settled on so far. I initially used a merge statement that is much more clean but unfortunately I discovered this function isn't available with SQL Server 2005. Next, I made a bastardized version of the code with Insert and Update with some choice if statements. This bastardized version appeared to have worked but I soon discovered that the update portion wasn't working. I then decided to cut out the update and just truncate and insert again each morning. This worked great for what I needed until I discovered that the job was inserting duplicate records into the table. To combat this, I created a primary key on the table. I ran the job manually and the table worked fine.

To automate this process I made this truncate/insert into a SQL Server job to run every morning before work hours and life was good. Turns out the next day this job fails to complete because I got a primary key violations. The code is still trying to input a duplicate. If I run this code manually through SQL Server job agent I receive no errors. If I let the job run as scheduled normally each morning it fails.

Is there anything in SQL Server job agent that is causing SQL Server to behave differently or process code differently? I don't understand how the system cannot run this code automatically using the same tool whereas I can I run it manually using the same tool and it works fine?

Try changing the time of day the job runs and see it that helps. It could be an issue with something else that just happens to be running at that same time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM