1

This is my query, but I am getting an error. Please help how to do it

declare @spid varchar(20)

if exists ((select @spid = Sponsor_Id  from UserTransaction)  where User_id= 'RL0814')
   insert into UserTransaction(Sponsor_Id, User_Id) 
   values (@spid,'RL4108')

The error is:

Incorrect syntax near '='

1 Answer 1

1

Try this instead:

DECLARE @spid VARCHAR(20)
SET @spid = NULL

SELECT @spid = Sponsor_Id 
FROM dbo.UserTransaction 
WHERE User_id = 'RL0814'

IF @spid IS NOT NULL
   INSERT INTO dbo.UserTransaction(Sponsor_Id, User_Id) 
   VALUES (@spid, 'RL4108')
Sign up to request clarification or add additional context in comments.

4 Comments

I need to store the result of the select statement in a variable,@spid, and then insert
@sumedha: OK, changed my response to meet your needs - in that case, just SELECT that value, and if it's NULL, then it doesn't exist, so you cannot insert. If it's NOT NULL, you can insert
Thanks,but is there no way I can use if exists..doing the same?
@sumedha: no, if you need to actually get the value, you cannot use IF EXISTS

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.