What version of SQL Server? This information is always useful, so please read the topic of the question with a specific version.
If sql-server-2008 or more, you can consider MERGE instead of separate INSERT / UPDATE operations, although after writing this answer I definitely changed my setting and preferred the UPDATE / IF @@ROWCOUNT = 0 / INSERT methodology you proposed. For more information see this article I wrote:
Here is an example of MERGE (run it in tempdb), but again recommend against it at all.
CREATE TABLE dbo.DataType ( ID int IDENTITY(1,1), TypeName nvarchar(255), [TypeProperty] nvarchar(255), CONSTRAINT PK_DataType PRIMARY KEY (ID) ); INSERT dbo.DataType(TypeName, [TypeProperty]) VALUES (N'name 1', N'property 1'); GO
Then follow the procedure:
CREATE PROCEDURE dbo.MergeDataType @ID int = NULL, @TypeName nvarchar(255), @TypeProperty nvarchar(255) AS BEGIN SET NOCOUNT ON; WITH [source](ID, TypeName, [TypeProperty]) AS ( SELECT @ID, @TypeName, @TypeProperty ) MERGE dbo.DataType WITH (HOLDLOCK) AS [target] USING [source] ON [target].ID = [source].ID WHEN MATCHED THEN UPDATE SET [target].TypeName = @TypeName, [target].[TypeProperty] = @TypeProperty WHEN NOT MATCHED THEN INSERT (TypeName, [TypeProperty]) VALUES (@TypeName, @TypeProperty); END GO
Now run it and check the results:
EXEC dbo.MergeDataType @TypeName = N'foo', @TypeProperty = N'bar'; EXEC dbo.MergeDataType @ID = 1, @TypeName = N'name 1', @TypeProperty = N'new property'; GO SELECT ID, TypeName, [TypeProperty] FROM dbo.DataType; GO
Cleaning:
DROP TABLE dbo.DataType; DROP PROCEDURE dbo.MergeDataType;