Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hello there....I am new to sql and need to create a script. I know what I want it to do but dont know how to code it....Basically I have two tables (Resluts and ADUsers) that I would like to join on a particular field (Logon). I would like to return the rows that DO NOT match and insert them into a 3rd table called MissingADUsers. If they already exist (based on the logon field) I would like a status field to be updated from 1 to 2 then 3.I think it should go something like this... SELECT * FROM RESULTS, ALL ADUSERSINNER JOIN ON LOGONWHERE LOGON <> EXIST IN RESULTSIF <> EXIST INSERT INTO MISSINGADUSERBEGINIF EXISTS AND STATUS FLAG = 1THEN UPDATE STATUS TO 2ELSEIF EXISTS AND STATUS FLAG = 2THEN UPDATE STATUS TO 3Any help would be appreciated SQL gurus!Cheers
mwjdavidson
Aged Yak Warrior
735 Posts
Posted - 2007-05-10 : 10:18:24
Use two statements: one for the insert and one for the update.
INSERT INTO dbo.MissingADUsers (Field1, Field2, etc.)SELECT a.Field1, a.Field2, etc.FROM dbo.ADUsers AS aLEFT JOIN dbo.Results AS rON a.Logon = r.LogonWHERE r.Logon IS NULLUPDATE aSET a.StatusFlag = CASE a.StatusFlag WHEN 1 THEN 2 WHEN 2 THEN 3 ENDFROM dbo.ADUsers AS aJOIN dbo.Results AS rON a.Logon = r.LogonWHERE a.StatusFlag BETWEEN 1 AND 2