我有一个包含几个表的数据库。我需要在另一个表中插入新行后在一个表中添加一列。
Table A: id | Type | Category | ShortDesc | LongDesc | Active
Row 1 int(11), varchar, varchar,varchar,varchar,int
Row 2
Row 3
Table B: id | Row1-ShortDesc | Row2-ShortDesc | Row3-ShortDesc
Row 1 int(11), tiny(1), tiny(1), tiny(1) etc...
Row 2
Row 3
当我偶尔向 TableA 添加新行(项目)时,我希望在 TableB 中添加一个新列。 TableA 是一个长期发展的集合。由于明显的遗留原因,无法删除 TableA 中的行。
因此,当我向 TableA 插入一行时,我需要将另一列插入/附加到 TableB 中。
如有任何帮助,我们将不胜感激。
TIA。
最佳答案
从 SQL 训练中得出的答案
我终于能够在俄亥俄州辛辛那提的 MAX TRAINING 上利用 SQL Server 中的一个类派生并创建我的触发器解决方案。
--SQL代码 -- 创建一个名为 TableA 的表,它只保存触发器的一些数据 -- 该表有一个主键,种子为 1,增量为 1
CREATE TABLE TableA(
id int identity(1,1) PRIMARY KEY,
name varchar(60) NOT NULL,
shortDesc varchar(60) NOT NULL,
longDesc varchar(60) NOT NULL,
bigDesc TEXT NOT NULL
)
GO
-- 创建一个只有 ID 列的表 TableB。 ID 作为主键,种子为 1,增量为 1
CREATE TABLE TableB(
id int identity(1,1) PRIMARY KEY
)
GO
-- 只是为了查看两个表中没有任何内容。
select * from TableA
select * from TableB
GO
-- TableA 中基于插入的实际触发器
CREATE TRIGGER TR_myInserCol
ON TableA
AFTER INSERT
AS
BEGIN
-- Don't count the trigger events
SET NOCOUNT ON;
-- Because we are making strings we declare some variables
DECLARE @newcol as varchar(60);
DECLARE @lastRow as int;
DECLARE @sql as varchar(MAX);
-- Now fill the variables
-- make sure we are looking at the last, freshly inserted row
SET @lastRow = (SELECT COUNT(*) FROM TableA);
-- Make a SELECT statement for the last row
SET @newcol = (SELECT shortDesc FROM TableA WHERE id = @lastRow);
-- Adds a new column in TableB is inserted based on a
-- TableA.shortDesc as the name of the new column.
-- You can use any row data you want but spaces and
-- special characters will require quotes around the field.
SET @sql = ('ALTER TABLE TableB ADD ' + @newcol + ' char(99)');
-- And run the SQL statement as a combined string
exec(@sql);
END;
GO
--向 TableA 中插入新行 --触发器将触发并在 TableB 中添加一列
INSERT INTO TableA
(name,shortDesc,longDesc,bigDesc)
VALUES ('attract','Attraction','Attractions','Places to go see and have
fun');
GO
INSERT INTO TableA
(name,shortDesc,longDesc,bigDesc)
VALUES ('camp','Camp','CAMP GROUND','Great place to sleep next to a creek');
GO
(name,shortDesc,longDesc,bigDesc)
VALUES ('fuel','GasStation','Fueling Depot','Get gas and go');
GO
INSERT INTO TableA
(name,shortDesc,longDesc,bigDesc)
VALUES ('petstore','PetStore','Pet Store','Get a friend');
GO
-- 查看 TableA 中新创建的行和 TableB 中新创建的列
select * from TableA
select * from TableB
GO
-- 除非要删除新创建的表,否则不要执行。 -- 用它来删除你的表 -- 清理您的工作空间,以便您可以进行更改并重试。
DROP TABLE TableA;
DROP TABLE TableB;
GO
再次感谢那些试图帮助我的人。是的,我仍然明白这可能不是最好的解决方案,但对我来说这很有效,因为我每年只会在 TableA 中插入几次行,并且在接下来的几年里很可能会最多插入不到 300 行因为我正在使用的数据不会频繁更改,并且可以使用单个位 (T/F) 访问单行,因此我现在可以快速将 TableB 分配给位置和人员作为搜索条件,并生成一个不错的 SQL查询字符串,无需跨多个页面进行多次读取。再次感谢!
如果有人想添加或修改我所做的事情,我会洗耳恭听。这一切都是为了学习和分享。
迈克尔
关于mysql - SQL触发器: New row :tableA to new col in :tableB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28008394/