互换的青春
桌子的设计有点奇怪。理想情况下,ApplicationID应该是一个标识列,以便SQL Server为您自动增加它。但是,嘿,我们都处理一些无法控制的遗留系统。请参见下面的SQL提琴,以了解执行此操作的一种方法。显然,当您拥有999个以上的应用程序时,该应用程序将崩溃,因此您必须进行以下处理:MS SQL Server 2017架构设置:CREATE TABLE Application (Id varchar(3), ApplicationName varchar(max))CREATE TABLE AppCategory (Id varchar(2), CategoryName nvarchar(max))CREATE TABLE AppPerCategory (CategoryId varchar(2), ApplicationId varchar(3), SeqIndex int)INSERT Application VALUES ('091', 'foo')INSERT AppCategory VALUES ('00', 'test category')INSERT AppPerCategory VALUES ('00', '091', 1)查询1:-- Assume below two are inputs for creating new applicationDECLARE @newAppName varchar(max) = 'new application'DECLARE @category varchar(max) = 'test category'-- Below will set newAppId to 092. Not you have to adjust for when # apps > 999DECLARE @newAppId varchar(3) = (SELECT REPLACE(STR(CAST(MAX(Id) AS int) + 1, 3), ' ', 0) FROM Application)DECLARE @categoryId varchar(2) = (SELECT Id from AppCategory WHERE CategoryName = @category)DECLARE @newCategorySeqIndex int = (SELECT MAX(SeqIndex) + 1 FROM AppPerCategory WHERE CategoryId = @categoryId)INSERT Application (Id, ApplicationName) VALUES (@newAppId, @newAppName)INSERT AppPerCategory (CategoryId, ApplicationId, SeqIndex) VALUES (@categoryId, @newAppId, @newCategorySeqIndex)