Quantcast
Channel: Forum Getting started with SQL Server
Viewing all articles
Browse latest Browse all 7129

update the record in case it existed and insert in case it is not existed.

$
0
0

I have a stored procedure that supposed to update the record when it exists and insert the record in case it is not existed. For update I want store procedure only update the field that I give a value and keep the rest same as it was. I pass null for field that I don’t want to update, but it update that fields with null. What is the best way to have this kind of store procedure?

this is my code:

--exec insert_Or_Update_Agency 1,40503,1,null,'test description',null,null,null,null,null,null,null,null
alter  PROCEDURE [dbo].[insert_Or_Update_Agency] 
	 @_IdxIdentity				BIGINT      = NULL
	,@AID						INT         = NULL
	,@_IsActive                 bit        
	,@Name				        varchar(40) = NULL
	,@Description               varchar(200)= NULL
	,@ContactPhone              varchar(50) = NULL
	,@ContactName               varchar(100)= NULL
	,@ContactEmail			    varchar(100)= NULL
	,@Country					varchar(50) = NULL
	,@Street					varchar(100)= NULL
	,@City						varchar(100)= NULL
	,@State						varchar(50) = NULL
	,@zipCode					varchar(50)	= NULL

			  
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	 
    -- Insert statements for procedure here
	IF (@_IdxIdentity >0  AND EXISTS ( select 1 from Agency where _IdxIdentity=@_IdxIdentity and AID=@AID))
		BEGIN
			--Update
			UPDATE Agency
			SET
			  _IsActive        = @_IsActive
			  ,Name            = @Name
			  ,[Description]   = @Description
			  ,ContactPhone    = @ContactPhone
			  ,ContactName     = @ContactName
			  ,ContactEmail    = @ContactEmail
			  ,Country         = @Country
			  ,Street          = @Street
			  ,City            = @City
			  ,[State]         = @State
			  ,zipCode         = @zipCode				
			WHERE _IdxIdentity = @_IdxIdentity and AID=@AID
		END
	ELSE
		BEGIN
			--Insert
			INSERT INTO Agency
			(
			  _IsActive
			  ,Name
			  ,[Description]
			  ,ContactPhone
			  ,ContactName
			  ,ContactEmail
			  ,Country
			  ,Street
			  ,City 
			  ,[State]
			  ,zipCode		
			)
			VALUES
			(
			   @_IsActive
			  ,@Name
			  ,@Description
			  ,@ContactPhone
			  ,@ContactName
			  ,@ContactEmail
			  ,@Country
			  ,@Street
			  ,@City 
			  ,@State
			  ,@zipCode		
			)
		END
END


Viewing all articles
Browse latest Browse all 7129

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>