1

在包含许多表的数据库中,如果数据不存在,我需要编写一个 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         |

我需要插入:

  1. currency( id=3, Code=JPY, lastupdate=today, rate=4)
  2. client( id=6, name=Joe, createdate=today, currencyId=Currency with Code 'USD')
  3. account( id=9, number=0910, createdate=today, clientId=Client with name 'Joe')

问题:

  1. 脚本必须在插入新数据之前检查行是否存在
  2. 脚本必须允许我们将外键添加到新行,该外键与数据库中已找到的行相关(如客户表中的 currencyId)
  3. 脚本必须允许我们将当前日期时间添加到插入语句中的列(例如createdateclient表中)
  4. 脚本必须允许我们向新行添加外键,该外键与插入同一脚本中的行相关(例如clientIdaccount表中)

注意:我尝试了以下 SQL 语句,但它只解决了第一个问题

INSERT INTO Client (id, name, createdate, currencyId)
SELECT 6, 'Joe', '05-11-2012', 1
WHERE not exists (SELECT * FROM Client where id=6);

此查询运行时没有任何错误,但正如您所看到的我手动编写createdatecurrencyid,我需要从带有 where 子句的 select 语句中获取货币 id(我试图用 select 语句替换 1,但查询失败)。

这是一个关于我需要的示例,在我的数据库中,我需要这个脚本在 10 多个表中插入 30 多行。

任何帮助

4

2 回答 2

0

你写了

我试图用 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-11T08:50:46.317 回答
0

看起来您可以确定数据是否存在。这是用 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
于 2012-05-11T08:57:32.510 回答