0

My procedure

 ALTER PROCEDURE [dbo].[spMyProc]
 @uniqueid  uniqueidentifier,
 @y int

DECLARE @ID uniqueidentifier
 SELECT TOP 1 @ID = uniqueid FROM tbl_x WHERE y= @y

INSERT INTO tbl_x
(   
    otherfield
    ,uniqueid   
)
VALUES
(
   @otherfields
   ,if @ID == null then @uniqueid else @ID -- this is what i want to happen how i do not know
)

Now i can do this using if else block like this but i do not want to do it. I want some nice way of coding this

this is what i do not want to do

if(@id IS NULL)
BEGIN
INSERT INTO tbl_x
(   
    otherfield
    ,uniqueid   
)
VALUES
(
   @otherfields
   ,@uniqueid 
)
END
ELSE
BEGIN
INSERT INTO tbl_x
(   
    otherfield
    ,uniqueid   
)
VALUES
(
   @otherfields
   ,@id 
)
END

is there any suggestion

3 Answers 3

4

you can use insert into select like this

INSERT INTO tbl_x
(   
    otherfield
    ,uniqueid   
)
SELECT 
  @otherfields,
  ISNULL(@ID , @uniqueid)
Sign up to request clarification or add additional context in comments.

2 Comments

you can combine the two select statements into this to have one statement. with this you need a table lock to be sure there are no deadlocks or other problems. With one statement (by combining) the server will take care of it.
Cool it is working fine. Thanks. I did discover this works as well CASE WHEN .. = null THEN .. else .. END. I am adding dots coz comments does not let me enter @
0

You can put your IF into the SELECT where you assign the value:

ALTER PROCEDURE [dbo].[spMyProc]
 @uniqueid  uniqueidentifier,
 @y int

DECLARE @ID uniqueidentifier
 SELECT TOP 1 @ID = ISNULL(uniqueid,@uniqueid) FROM tbl_x WHERE y= @y

INSERT INTO tbl_x
(   
    otherfield
    ,uniqueid   
)
VALUES
(
   @otherfields
   ,@ID
)

Comments

0

you can use CASE while inserting values

INSERT INTO tbl_x
(   
    otherfield
    ,uniqueid   
)
VALUES
(
   @otherfields
   ,CASE WHEN @ID IS NULL THEN @uniqueid ELSE @ID END
)

or you can also use ISNULL function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.