I’m having trouble understanding what this query accomplishes:
DECLARE @CatalogID int
INSERT [Catalog] ([Name])
SELECT @Catalog WHERE NOT EXISTS (SELECT [Name] FROM [Catalog] WHERE [Name] = @Catalog)
SELECT @CatalogID = ID FROM [Catalog] WHERE [Name] = @Catalog
The schema comprises of five tables catalogue, data entry, dataentryversion, tags, users
Basically you’re inserting a record if it doesn’t already exist and then returning the ID of the record that was either inserted, or was already there.
I’ve added comments to the code below:
For what it’s worth, it is possible to write this query the other way around, i.e. selecting the matching record out of
catalogand if nothing is returned then performing the insert but this approach is superior in that it is not vulnerable to a ‘race condition’ where two processes may be trying to insert the same record at the same time.