为了账号安全,请及时绑定邮箱和手机立即绑定

如何向具有多列作为主键的SQL Server表中添加新行

如何向具有多列作为主键的SQL Server表中添加新行

C#
慕桂英546537 2021-03-30 17:06:28
我在SQL Server中有一个多对多关系表。表:应用表:AppCategory表:AppPerCategory主键[AppPerCategory]为CategoryID + AppID。在主键[Application]和[AppPerCategory]没有在序列/顺序。那么,如何[Application]使用C#,ASP.NET WebForms向添加新行呢?我正在构建一个小的C#ASP.NET Web表单,以允许用户向[Application]表中添加新行。
查看完整描述

1 回答

?
互换的青春

TA贡献1797条经验 获得超6个赞

桌子的设计有点奇怪。理想情况下,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 application

DECLARE @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 > 999

DECLARE @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)


查看完整回答
反对 回复 2021-04-10
  • 1 回答
  • 0 关注
  • 174 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信