Search code examples
sqlsql-serverxmlsql-updatesqlxml

How to write UPDATE from XML with Table Alias in SQL Server 2008 already have a 'From' statement


Here I need to add an Alias name to 'TableName' AS T. The Update already have a 'From' statement for getting value from XML.

UPDATE TableName SET 
  TableName.PrintedBy = ISNULL(TableName.PrintedBy,der.PrintedBy), 
  TableName.PrintedDate = ISNULL(TableName.PrintedDate,GETDATE()),
  @RetVal=der.NoteId 
FROM (     
SELECT PrintedBy,NoteId
      FROM OPENXML(@hDoc1,'TableName',1)
      WITH   (  PrintedBy INT 'PrintedBy', 
                NoteId INT 'NoteId'
             )
    ) as der
WHERE TableName.NoteId = der.NoteId 

Solution

  • Try this,

    UPDATE T SET 
    T.PrintedBy = ISNULL(T.PrintedBy,der.PrintedBy), 
    T.PrintedDate = ISNULL(T.PrintedDate,GETDATE()),
    @RetVal=der.NoteId 
    FROM (     
        SELECT PrintedBy,NoteId
        FROM OPENXML(@hDoc1,'TableName',1)
        WITH   (  PrintedBy INT 'PrintedBy', 
                  NoteId INT 'NoteId'
                )
         ) as der, TableName T
    WHERE T.NoteId = der.NoteId