4

我怎样才能做到这一点……真的需要建议吗?我想获取满足我的条件的 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
4

3 回答 3

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
于 2013-01-31T05:48:02.440 回答
1

在 SQL Server 中。该脚本首先插入记录,然后检查插入行的计数

  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'
于 2013-01-31T08:29:24.397 回答
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
于 2013-01-31T06:39:02.010 回答