两张表A , B
都有字段ID
现在要从A表取最大ID值插入到B表ID字段中 (如果A表为空,则不插入)
我之前是这样写的
insert into A(ID) select max(ID) from B
但是这个语句没考虑到A表空的问题,当A表为空或者MAX(ID)为NULL的时候,上述语句也会插入NULL到B表
现在我要排除max(ID)为空的时候
用一条语句怎么写?
SQL 复制,插入
------解决方案--------------------
到底是A-》B 还是B-》A啊
insert into A(ID) select max(ID) from B where id<>''
------解决方案--------------------
try this,
if (select max(ID) from B) is not null
begin
insert into A(ID) select max(ID) from B
end
------解决方案--------------------
如果id是数值的话
insert into A(ID) select max(ID) from B where id is not null
------解决方案--------------------
insert into A(ID) select max(ID) from B where id is not null
这样?
另外你的题目中表名好像反了
------解决方案--------------------
select top 1 id from b order by id desc
这个也试试。
------解决方案--------------------
DECLARE @id INT
SELECT @id=MAX(ID) FROM A
IF @id IS NULL
RETURN
ELSE
INSERT INTO B SELECT @id
------解决方案--------------------
inert into B(id) select id from A where id is not null