Easysoft Blog

Mon, December 18 2017

Updating Salesforce Data with a SQL Server Cursor

Easysoft customers use our Salesforce.com ODBC Driver to work with Salesforce.com data in SQL Server. The following example shows how to update a Salesforce record from SQL Server by using a cursor:

  1. Configure a linked server that connects to Salesforce.
  2. Change the Linked Server > Linked Server Properties > Server Options > RPC Out setting to True.
  3. Adapt and then execute the following SQL:
    -- This example changes the name of an account to 'GenePoint Inc'.
    DROP TABLE Account
    SELECT * INTO ACCOUNT FROM OPENQUERY(SFLINKEDSERVER,'SELECT ID, NAME FROM Account
                                         WHERE Id=''001i000000AOq3DAAT''')
    SELECT * FROM ACCOUNT
    UPDATE ACCOUNT SET [Name]='GenePoint Inc'
    SELECT * FROM ACCOUNT
    
    DECLARE @Id NVARCHAR(18)
    DECLARE @Name NVARCHAR(255)
    DECLARE @SQL NVARCHAR(MAX)
    
    DECLARE LocAccCur CURSOR FOR SELECT Id, REPLACE([Name],'''', '''''') FROM Account
    OPEN LocAccCur
    FETCH NEXT FROM LocAccCur INTO @Id, @Name
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT 'Id : ' + @Id
        PRINT 'Name : ' + @Name
        SELECT @SQL='UPDATE Account SET [Name]='''+@Name+''' WHERE Id='''+@Id+''''
        EXEC(@SQL) at SFLINKEDSERVER
        FETCH NEXT FROM LocAccCur INTO @Id, @Name
    END
    CLOSE LocAccCur
    DEALLOCATE LocAccCur
    

See Also