Q:

SQL 2005 stored procedure to return value or create it if it does not exist

I am having trouble with a stored procedure (SQL 2005).
I have a table called tbrm_Tags with two columns, TagID and TagName. I want to pass a TagName value to the stored procedure and then I want to:

Check if the Tagname exists and if it does return the TagID
If the Tagname does not exist I want it to insert into the table and return the TagID.

Here is the stored procedure I am using:
  @TagID int = null,
  @TagName varchar(50)  

AS

DECLARE @returnValue int

  BEGIN
  IF EXISTS (SELECT * FROM tbrm_Tags WHERE TagName = @TagName)
  BEGIN

  SELECT

  TagID

  FROM tbrm_Tags

  WHERE TagName = @TagName

END
ELSE
BEGIN
IF NOT EXISTS (SELECT * FROM tbrm_Tags WHERE TagName = @TagName)

   INSERT INTO tbrm_Tags

  (
    TagName

  )
  VALUES
  (
    @TagName

      )

  SELECT @returnValue = @@IDENTITY

  END
  END

  RETURN @returnValue

I cannot get the select statement to return the TagID when the Tagname exists.

A:

Note: don't use @@IDENTITY - it is subject to triggers; always use SCOPE_IDENTITY()
I might just do:
DECLARE @returnValue int

SELECT @returnValue = TagID
FROM tbrm_Tags
WHERE TagName = @TagName

IF @returnValue IS NULL
BEGIN
     INSERT tbrm_Tags(TagName)
     VALUES (@TagName)

     SET @returnValue = SCOPE_IDENTITY()
END

RETURN @returnValue

A:

SELECT

@returnValue = TagID

FROM tbrm_Tags

WHERE TagName = @TagName

