4

How can I make this possible..really need advice? I want to get the id where my condition is met, then used it in my queries.

   IF EXISTS (Select sn_id as snid FROM device.sn WHERE dname_id = 62 and sn_value = '123415')
    BEGIN

    SELECT MAX(id) AS maxid FROM device.list 

    INSERT INTO parts (sn_id,device_id) VALUES (snid, maxid)

    END
    ELSE
    BEGIN
      PRINT 'id does not exist'
    return 
    END
1
  • 1
    Which database server are you using? my-sql? ms-sql-server? Commented Jan 31, 2013 at 5:45

3 Answers 3

3

You can use variables to store the results from the two queries and then use those values in your INSERT statement.

If you're using Microsoft SQL Server then the following may work (but there may be superficial syntax errors as it hasn't been tested). Note that I've assumed the type of your columns is int.

DECLARE @snid int
SET @snid = NULL
Select @snid = sn_id FROM device.sn WHERE dname_id = 62 and sn_value = '123415'

IF @snid IS NULL
BEGIN
  PRINT 'id does not exist'
END
ELSE
BEGIN
  DECLARE @maxid int
  SELECT @maxid = MAX(id) AS maxid FROM device.list 
  INSERT INTO parts (sn_id,device_id) VALUES (@snid, @maxid)
END
Sign up to request clarification or add additional context in comments.

1 Comment

Your a SQL god,daniel. Thank you.
1

In SQLServer. This script at first insert records and after checks count of the inserted rows

  INSERT INTO parts (sn_id, device_id)    
  SELECT sn_id, (SELECT MAX(id) FROM device.list)
  FROM device.sn 
  WHERE dname_id = 62 and sn_value = '123415'  

  IF @@ROWCOUNT = 0 PRINT 'id does not exist'

1 Comment

op might not know the insert into..select pattern. explaining may help him.
0
Declare @snid int=null
Declare @maxid int=1 -- if no value exists in device.list table
set @snid = (select sn_id from device.sn WHERE dname_id = 62 and sn_value = '123415')
set @maxid = (select MAX(id) AS maxid FROM device.list)
if @snid is not null
Begin
  insert into parts(sn_id,device_id)
  values(@snid,@maxid)
End
else
Begin
  print 'ID does not exist'
End

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.