在包含多个表的数据库中,如果不存在数据,则需要编写SQL脚本来插入数据。
表货币
| id | Code | lastupdate | rate |
+--------+---------+------------+-----------+
| 1 | USD | 05-11-2012 | 2 |
| 2 | EUR | 05-11-2012 | 3 |
表客户端
| id | name | createdate | currencyId|
+--------+---------+------------+-----------+
| 4 | tony | 11-24-2010 | 1 |
| 5 | john | 09-14-2010 | 2 |
表:帐户
| id | number | createdate | clientId |
+--------+---------+------------+-----------+
| 7 | 1234 | 12-24-2010 | 4 |
| 8 | 5648 | 12-14-2010 | 5 |
我需要插入:
currency
(id=3, Code=JPY, lastupdate=today, rate=4
)client
(id=6, name=Joe, createdate=today, currencyId=Currency with Code 'USD'
)account
(id=9, number=0910, createdate=today, clientId=Client with name 'Joe'
)问题:
在插入新数据之前,必须检查行是否存在,table)
client
中的createdate
)必须允许我们在新行中添加外键,其中外键与插入在同一脚本中的行(例如account
表中的clientId
)
G 238
有关。
注意:我尝试了以下语句,但它只解决了第一个问题
INSERT INTO Client (id, name, createdate, currencyId)
SELECT 6, 'Joe', '05-11-2012', 1
WHERE not exists (SELECT * FROM Client where id=6);
这个查询运行时没有任何错误,但正如您看到的,我手动编写了createdate
和currencyid
,我需要从带有where子句的select语句中获取货币id (我试图用select语句替换1,但查询失败)。
这是我需要的一个例子,在我的数据库中,我需要这个脚本在10个以上的表中插入超过30行。
任何帮助
发布于 2012-05-11 00:50:46
你写的
I试图用select语句替换1,但查询失败
但我不知道为什么失败了?你试过什么?这应该是可行的:
INSERT INTO Client (id, name, createdate, currencyId)
SELECT
6,
'Joe',
current_date,
(select c.id from currency as c where c.code = 'USD') as currencyId
WHERE not exists (SELECT * FROM Client where id=6);
发布于 2012-05-11 00:57:32
看起来你可以计算出数据是否存在。下面是用SQL Server / Sybase编写的快速代码,我认为这些代码可以回答基本问题:
create table currency(
id numeric(16,0) identity primary key,
code varchar(3) not null,
lastupdated datetime not null,
rate smallint
);
create table client(
id numeric(16,0) identity primary key,
createddate datetime not null,
currencyid numeric(16,0) foreign key references currency(id)
);
insert into currency (code, lastupdated, rate)
values('EUR',GETDATE(),3)
--inserts the date and last allocated identity into client
insert into client(createddate, currencyid)
values(GETDATE(), @@IDENTITY)
go
https://stackoverflow.com/questions/10547403
复制相似问题