SQL 2008에서 SP를 만들고 싶습니다. 데이터베이스에 이미 값이 있으면 ID를 반환하고 그렇지 않으면 값을 삽입하고 새로 삽입 된 값의 ID를 반환합니다.ID 가져 오기 또는 삽입 ID 용
create table YourTable (id int identity, name nvarchar(50))
go
create procedure dbo.YourSp(
@name varchar(50))
as
declare @id int
set transaction isolation level serializable
begin transaction
select @id = id from dbo.YourTable where name = @name
if @id is null
begin
insert dbo.YourTable (name) values (@name)
set @id = scope_identity()
end
commit transaction
return @id
go
이 같은 테스트 경우 :
declare @rc int
exec @rc = dbo.YourSp 'John'; select @rc
exec @rc = dbo.YourSp 'John'; select @rc
exec @rc = dbo.YourSp 'George'; select @rc
을 그것은 것 테이블 여기
Title { Id(int), Name(nvarchar(50) }
ID는 ID 열입니까? –
왜이 작업을 수행 하시겠습니까? 알려진 id 값을 보내는 경우 이미 레코드가 있다는 것을 알고 있지 않습니까? – HLGEM