I’m working with SQL Server 2005 and need to replicate the behavior of MySQL’s REPLACE INTO
statement. This MySQL command is really handy because it automatically inserts a new record or updates an existing one if there’s a duplicate key.
-- Example of what I want to achieve
-- Instead of separate INSERT/UPDATE logic
IF EXISTS (SELECT 1 FROM employees WHERE emp_id = @id)
UPDATE employees SET name = @empName, salary = @empSalary WHERE emp_id = @id
ELSE
INSERT INTO employees (emp_id, name, salary) VALUES (@id, @empName, @empSalary)
Right now I have to write separate logic to check if a record exists, then decide whether to insert or update. This means maintaining two different SQL statements in my application code, which gets messy.
Is there a built-in way or a standard pattern in SQL Server 2005 to handle this insert-or-update scenario more elegantly? I’m looking for something that works consistently across different tables without having to write custom logic each time.