简体   繁体   中英

Create stored procedure in SQL Server from a MS Access update query

I'm trying to create my first stored procedure.

I did copy the following SQL from MS Access to a SQL Server stored procedure and I have "LEFT JOIN" syntax errors. What's wrong with?

UPDATE dbo.AssemblyInstanceMassProperties
LEFT JOIN dbo.BOM ON dbo.AssemblyInstanceMassProperties.ID = dbo.BOM.AssemblyInstanceID
SET dbo.AssemblyInstanceMassProperties.NumberofSubInstance = 1
WHERE (((dbo.BOM.AssemblyInstanceID) IS NULL));

In TSQL for an update involving multiple tables you should always write a SELECT statement first and UPDATE that. And always use table aliases. And always terminate each statement with a ;.

So first write a query that returns the rows you want to update, explicitly listing all columns involved in the UPDATE:

SELECT p.NumberofSubInstance, *
FROM dbo.AssemblyInstanceMassProperties p
LEFT JOIN dbo.BOM b
ON p.ID = b.AssemblyInstanceID
 WHERE b.AssemblyInstanceID Is Null;

then when you're confident you've got the right rows turn it into an UPDATE like this:

with q as
(
    SELECT p.NumberofSubInstance
    FROM dbo.AssemblyInstanceMassProperties p
    LEFT JOIN dbo.BOM b
    ON p.ID = b.AssemblyInstanceID
     WHERE b.AssemblyInstanceID Is Null
)
update q set NumerOfSubInstance = 1;

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