I need a query that will RETRIEVE a value from a database if it is present, but if the data isn't present, then the data will be INSERTed into the table.
Either way, I need the row returned at the end of the query.
I can do SELECT queries, but I don't have a clue as to how to proceed with branching statements.
For example:
User runs a query for "Canada".
Canada exists in the database, so the database returns Canada along with its ID.
Next user runs a query for "Chile".
Chile isn't in the database so a record is created and the ID (an IDENTITY field) is returned.
Does anyone know how I may accomplish this?something like this:
|||or
create proc MyProc
(
@.countryid int out,
@.countryname nvarchar(50)
)set @.countryid = -1
select @.countryid = CountryId
from MyTable
where CountryName = @.countrynameif (@.countryid = -1)
begin
insert into MyTable (CountryName)
values (@.countryname)select @.countryid = scope_identity()
end
IF NOT EXISTS ( Select countryId from from MyTable where CountryName = @.countryname)
INSERT INTO MyTable (CountryName) values (@.countryname)
hth
No comments:
Post a Comment