[英]Insert into two tables and affect the id of one of the table columns into the other table
I have a Folder table which contain the following colomuns 我有一个包含以下项的文件夹表
id | name | state | imageFolder
-------------------------------------------
1 NameTest 1 2
And i have another one called Images which contain 我还有一个叫做“图片”的图片,其中包含
id | url
--------------------------------------------
2 https://www.someImageUrl
I want to insert an url in the folder table in a query and put it in the images and get the id in the same query. 我想在查询的文件夹表中插入一个url并将其放在图像中,并在同一查询中获取id。 Actually, i am working an android project, i have to add a new folder and upload an image to it so that's why i'm in need of this. 实际上,我正在一个android项目中,我必须添加一个新文件夹并将图像上传到它,因此这就是为什么我需要这个。 Is there a way to do it ?? 有办法吗?
You'll want to use SCOPE_IDENTITY()
to capture the key value being generated by the IMAGE
table. 您将要使用SCOPE_IDENTITY()
捕获由IMAGE
表生成的键值。 Some people use @@IDENTITY
, do not do that, it has a global scope and you can sometimes get back the wrong ID. 有些人使用@@IDENTITY
,不要这样做,它具有全局作用域, 有时您可能会获取错误的ID。
Then use that value to insert into the FOLDER
table. 然后使用该值插入FOLDER
表。 It feels a little backwards to insert into the IMAGE
table first but that's how you get the ID
you want. 首先插入IMAGE
表有点后退,但这是您获取所需ID
。 Here is a fully functional example: 这是一个功能齐全的示例:
IF OBJECT_ID('IMAGE') IS NOT NULL
DROP TABLE [IMAGE]
CREATE TABLE [dbo].[IMAGE](
[id] [int] IDENTITY(1,1) NOT NULL,
[url] [varchar](50) NOT NULL,
CONSTRAINT [PK_IMAGE] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
IF OBJECT_ID('FOLDER') IS NOT NULL
DROP TABLE [FOLDER]
CREATE TABLE [dbo].[FOLDER](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NOT NULL,
[state] [int] NOT NULL,
[image_id] [int] NOT NULL,
CONSTRAINT [PK_FOLDER] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
DECLARE @IMAGE_ID INT
INSERT INTO IMAGE(url)
VALUES ('http://www.example.com')
SET @IMAGE_ID = SCOPE_IDENTITY() --This is the key part
INSERT INTO FOLDER(NAME, STATE, IMAGE_ID)
VALUES ('NameTest', 1, @IMAGE_ID)
GO
SELECT * FROM IMAGE
SELECT * FROM FOLDER
Results: 结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.