SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Update vs Insert from Query
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

bholmstrom
Yak Posting Veteran

USA
71 Posts

Posted - 03/27/2013 :  16:21:48  Show Profile  Reply with Quote
I have a query that gets active directory name information and then inserts the data into a sql table. This process is no longer since the owner now wants to update the table - not truncate it and rebuild it.

Here is the code:

SET @adsiQuery = N'SELECT userPrincipalName, givenName, cn, ' +
'DisplayName, title, sAMAccountName, distinguishedName ' +
'FROM OPENQUERY (ADSI, ''SELECT userPrincipalName, givenName, sn ' +
'Displayname, title, sAMAccountName, distinguishedName,mail ' +
'FROM ''''LDAP://DC=RL-DC05,DC=jhcohn,DC=com'''' ' +
'WHERE objectClass = ''''User'''' ' +
'and title = ''''*'''' ' +
'AND sn = ''''<alpha>*'''''')'


USE NCOS_Dev


SET @alpha = ASCII('A')
WHILE @alpha <= ASCII('Z')
BEGIN
SET @sql = N'INSERT NCOS_DomainUser ' +
'( DisplayName,sAMAccountName,GivenName,cn,Title,DistinguishedName, ' +
'userPrincipalName,mail ) ' +
REPLACE(@adsiQuery, '<alpha>', CHAR(@alpha))
EXEC(@sql)
SET @alpha = @alpha + 1
END

---------------

So what I want to do is search for the user in the table first and if not found, INSERT. If found update certain fields.

Thanks for all of your help


Bryan Holmstrom

SwePeso
Patron Saint of Lost Yaks

Sweden
30249 Posts

Posted - 03/27/2013 :  17:44:03  Show Profile  Visit SwePeso's Homepage  Reply with Quote
Use MERGE

MERGE ...
USING ...
WHEN MATCHED THEN UPDATE
WHEN NOT MATCHED BY TARGET THEN INSERT



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000