首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >编写SQL脚本插入数据

编写SQL脚本插入数据
EN

Stack Overflow用户
提问于 2012-05-11 07:42:31
回答 2查看 6.4K关注 0票数 1

在包含多个表的数据库中,如果不存在数据,则需要编写SQL脚本来插入数据。

货币

代码语言:javascript
代码运行次数:0
运行
复制
| id     | Code    | lastupdate | rate      |
+--------+---------+------------+-----------+
| 1      | USD     | 05-11-2012 | 2         |
| 2      | EUR     | 05-11-2012 | 3         |

客户端

代码语言:javascript
代码运行次数:0
运行
复制
| id     | name    | createdate | currencyId|
+--------+---------+------------+-----------+
| 4      | tony    | 11-24-2010 | 1         |
| 5      | john    | 09-14-2010 | 2         |

表:帐户

代码语言:javascript
代码运行次数:0
运行
复制
| 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')

问题:

在插入新数据之前,必须检查行是否存在,table)

  • script脚本必须允许我们在新行中添加外键,如果该外键与数据库中已经找到的行相关(因为客户端table)

  • script中的currencyId必须允许我们将当前日期时间添加到insert语句中的列中(例如client中的createdate )必须允许我们在新行中添加外键,其中外键与插入在同一脚本中的行(例如account表中的clientId )

G 238有关。

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

代码语言:javascript
代码运行次数:0
运行
复制
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行。

任何帮助

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-05-11 08:50:46

你写的

I试图用select语句替换1,但查询失败

但我不知道为什么失败了?你试过什么?这应该是可行的:

代码语言:javascript
代码运行次数:0
运行
复制
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);
票数 0
EN

Stack Overflow用户

发布于 2012-05-11 08:57:32

看起来你可以计算出数据是否存在。下面是用SQL Server / Sybase编写的快速代码,我认为这些代码可以回答基本问题:

代码语言:javascript
代码运行次数:0
运行
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10547403

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档