Transact-SQL / Check if name exists

A simple question here.

Context: A Transact-SQL table with an int primary key and a name that should also be unqiue (although this is not a primary key). Let them talk:

TableID INT,
TableName NVARCHAR(50)

I add new rows for this using a stored procedure (and thus specifying a TableName with a parameter).

Question: What is the best / easiest way to check if the already specified TableName parameter exists in the table and prevent the addition of a new row, if so?

Is it possible to do this directly in my AddNewRow stored procedure?

+3
source share
3 answers

SQL Server 2008, MERGE sproc:

MERGE INTO YourTable AS target
USING (VALUES (@tableName)) AS source (TableName)
    ON target.TableName = source.TableName
WHEN NOT MATCHED THEN
    INSERT (TableName) VALUES (TableName)

, TableName UNIQUE.

+6

TableName , .

, , , .

. .

+5

Unique Constraint , .

, ,

-, , , .

IF EXISTS (SELECT TOP(1) ColName FROM MyTable WHERE ColName=@myParameter)

If you use a unique constraint, you can also apply Unique Nonclustured indexas a result of a quick search together.

+2
source

Source: https://habr.com/ru/post/1760135/


All Articles