Часто приходится видеть такой вариант
IF NOT EXISTS ( SELECT * FROM CustomerINSERT INTO [Customer]
WHERE Name = @CustomerName )
INSERT INTO [Customer]
( [Name])
VALUES
( @CustomerName)
но существует ещё один
( [Name])
SELECT @CustomerName
WHERE NOT EXISTS ( SELECT * FROM Customer
WHERE Name = @CustomerName )
и небольшой тест для обоих вариантов
USE pubs
GO
CREATE TABLE Customer (
ID int IDENTITY(1,1) NOT NULL,
Name nvarchar(100) NOT NULL,
UNIQUE (Name)
)
GO
DECLARE @CustomerName nvarchar(100)
SET @CustomerName = 'Customer2'
IF NOT EXISTS ( SELECT * FROM Customer
WHERE Name = @CustomerName )
BEGIN
WAITFOR DELAY '00:00:05'
/* this 5 sec pause lets you insert same row from another QA window:
DECLARE @CustomerName nvarchar(100)
SET @CustomerName = 'Customer2'
INSERT INTO [Customer]
( [Name])
VALUES
( @CustomerName)
*/
INSERT INTO [Customer]
( [Name])
VALUES
( @CustomerName)
END
SET @CustomerName = 'Customer3'
INSERT INTO [Customer]
( [Name])
SELECT @CustomerName
WHERE NOT EXISTS ( SELECT * FROM Customer
WHERE Name = @CustomerName )
GO
select Object_Id('Customer')
DROP TABLE Customer
Обсуждение в форуме http://www.sqlservercentral.com/Forums/Topic563553-1376-1.aspx
Комментариев нет:
Отправить комментарий