I am adding ‘Tagging’ functionality in my web app. My applications table structures are as following;
Tag:
(TagId INT IDENTITY, TagName VARCHAR(60))
TaggedRecords:
(TaggedId INT IDENTITY, TagId, TaggedRecordId)
Now, I want when anyone adds a tag to any record then following action should be performed using a single sql query or using a stored procedure;
- The tag is already present in ‘Tag’ table or not?
- If the tag is present then it inserts a row in ‘TaggedRecords’ table
- Else if the tag is not present then first insert the tag in ‘Tag’ table and then get the Id of newly added tag and insert a record in ‘TaggedRecord’ table
Basically, I am more interested in doing these actions using a single query or at max two sql queries. I don’t wanna make multiple If-Else conditions in sql stored procedure.
Thanks,
How about this…
Not tested this but the theory should be sound 🙂
For another example of the OUTPUT usage see my post at this link
EDIT
As per comments below this version uses EXISTS…
Although I’m not sure (I reliase I’m arguing against myself here but so much of this stuff is an "it depends" answer!). This example actually would work best for more usage of new tags because it would only perform the EXISTS once and then continue whereas for an existing tag it would perform an EXISTS and then a SELECT.
Hmm, take your pick – or test both approaches under volume 🙂