T - SQL语句IF EXIST SELECT和INSERT

时间:2013-01-31 05:39:34

标签: sql-server tsql

我怎样才能做到这一点......真的需要建议吗?我希望得到满足条件的id,然后在我的查询中使用它。

   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

3 个答案:

答案 0 :(得分:3)

您可以使用变量存储两个查询的结果,然后在INSERT语句中使用这些值。

如果您使用的是Microsoft SQL Server,则以下内容可能有效(但可能存在表面语法错误,因为它尚未经过测试)。请注意,我假设您的列类型为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

答案 1 :(得分:1)

在SQLServer中。此脚本首先插入记录并在检查插入的行数后

  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'

答案 2 :(得分: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