我正在使用 SQL Server 2008 R2、C# 和 ASP.Net。我有一个表,它有一个由票号组成的复合主键,以及该票在表中出现的次数。通过 C# 代码计算出票频率:
VTTTickets.InsertParameters[0].DefaultValue = VTTTTicketNoBox.Text;
string CommString = "SELECT COUNT(*) FROM [Tickets] WHERE [Ticket_No] = " +
VTTTTicketNoBox.Text;
string ConnString = ConfigurationManager.ConnectionStrings[1].ConnectionString;
OdbcConnection Conn = new OdbcConnection(ConnString);
Conn.Open();
OdbcCommand FooCommand = newOdbcCommand(CommString,Conn);
int FooVal = Convert.ToInt32(FooCommand.ExecuteScalar()) + 1;
VTTTickets.InsertParameters[1].DefaultValue = Convert.ToString(FooVal);
VTTTTicketNoBox.Text = "";
Conn.Close();
我的表约束/等代码
CONSTRAINT [PK_Tickets] PRIMARY KEY CLUSTERED
([Ticket_No] ASC, [Ticket_Sub_No] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = ON,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [Unique_Ticket_No] UNIQUE NONCLUSTERED
([Ticket_No] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = ON,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
) ON [PRIMARY]
GO
唯一约束的原因是因为主复合键的那部分也是另外两个表的外键。我不断遇到的错误是当它对我大喊大叫时,因为唯一受约束的列中存在重复值。一旦一切从开发转移到生产,这可能会发生,因为可能会重新提交票证。
有没有办法在没有唯一键约束的情况下制作外键?如果没有,我该如何解决这个问题?