我想下面的2个表连接在一起:连接两台SQL Server表
CREATE TABLE [dbo].[Groups]
(
[Group_Id] INT IDENTITY (1, 1) NOT NULL,
[Group_Name] NVARCHAR (50) NULL,
[Group_Desc] NVARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([Group_Id] ASC)
);
CREATE TABLE [dbo].[Events]
(
[Event_Id] INT IDENTITY (1, 1) NOT NULL,
[Event_Group_Id] INT null,
[Event_Type] NVARCHAR (50) NULL,
[Event_Title] NVARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([Event_Id] ASC),
CONSTRAINT fk_event_group
FOREIGN KEY (Event_Group_Id) REFERENCES Groups (Group_Id)
);
第一个问题:有我创建的表是否正确?
我已经能够使用下面的代码添加到Events
,但是我还没有能够成功地将Groups
的PK作为Events
中的FK连接。
有没有人有任何建议?
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BallinoraDBConnectionString1"].ConnectionString);
conn.Open();
string findGroupOfEvent = "SELECT Group_Id FROM Groups WHERE Group_Name ='" + DropDownListEventGroup.SelectedItem.ToString() + "'";
int groupId = Convert.ToInt32(findGroupOfEvent);
string insertQuery = "INSERT INTO Events (Event_Group_Id, Event_Type, Event_Title) VALUES (@GroupEventID, @Type, @Title)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("@GroupEventID", groupId);
com.Parameters.AddWithValue("@Type", DropDownListEventType.SelectedItem.ToString());
com.Parameters.AddWithValue("@Title", TextBoxET.Text);
com.ExecuteNonQuery();
Response.Redirect("ViewEvents.aspx");
Response.Write("Registration is successful");
conn.Close();
'但我一直没能组的PK成功连接为FK在Events.' <=你这是什么意思?你也应该把你的SqlConnections封装在''using''块中,并且每次你想与数据库进行交互时都要创建一个新的实例(没有一个可重用的中心SqlConnection!)。另请参见[最佳实践 - 执行SQL语句](http://stackoverflow.com/documentation/.net/3589/ado-net/14261/best-practices-executing-sql-statements)。 – Igor
向Event表添加新行时,我有一个下拉菜单,其中包含与[Groups]的[Group_Name]中相同的文本。我希望能够获得与DropDown菜单中选择的[Group_Name]相同行的Group_ID,并将该值分配给[Events]表中的[Event_Group_ID]。 – user2911539
你没有提到任何UI,到目前为止,这个问题只显示了Sql DDL和ADO.NET。这部分代码对我来说看起来很好,只需要注意一下,你在'@ GroupEventID'参数中硬编码了'1',这可能是也可能不是你的意图。如果你需要下拉值的帮助,你应该显示相关的代码。 – Igor