The syntax error is because the target column names of the SET
clause should not be prefixed with an alias. No qualification is needed since the target columns are implicitly columns in the target table.
Below is a corrected example that also includes parameters for @divisionkey
and @divisionname
instead of injecting the values with string concatenation. Note I just guessed at the parameter data types for the example; change to match your actual column data types.
SET @sqlCommand = '
MERGE' + @schemaname + '.[DimSalesOffice] so USING #temptable tt
ON (so.sales_division = @divisionname and so.[SalesOfficeCode] = tt.SALES_OFFICE)
WHEN MATCHED
THEN
UPDATE
SET
[SalesOfficeCode] = tt.SALES_OFFICE,
[SalesOfficeName] = tt.OFFICE_NAME,
[PriceList] = tt.PriceList,
[DivisionKey] = @divisionkey
WHEN NOT MATCHED
THEN
INSERT ([SalesOfficeCode],[SalesOfficeName],[PriceList],[DivisionKey])
Values (tt.SALES_OFFICE, tt.OFFICE_NAME,tt.PriceList,@divisionkey)
;';
EXEC sp_executesql
@sqlCommand
, N'@divisionname varchar(30), @divisionkey varchar(30)'
, @divisionname = @divisionname
, @divisionkey = @divisionkey;