如何检查一个表的ID是否等于另一个表的ID,如果相等则将新值赋给asp.net

时间:2017-05-19 16:05:13

标签: c# sql asp.net database webforms

我正在尝试构建一个测验应用程序。我创建了两个表:

CREATE TABLE [dbo].[Answers] (
       [AID]           INT            NOT NULL,
       [QID]           INT            NOT NULL,
       [Answer]        NVARCHAR (200) NOT NULL,
       [CorrectAnswer] NVARCHAR (200) NULL,
       PRIMARY KEY CLUSTERED ([AID] ASC),
       CONSTRAINT [FK_Answers_Question] FOREIGN KEY ([QID]) REFERENCES [dbo].         
       [Question] ([QID])
        );

CREATE TABLE [dbo].[Question] (
       [QID]      INT            IDENTITY (1, 1) NOT NULL,
       [Question] NVARCHAR (200) NOT NULL,
       PRIMARY KEY CLUSTERED ([QID] ASC)
 );

这里,QID是自动生成并递增的。 答案表包含AID作为主键,QID作为外键。 现在我的问题是我应该自动生成并增加Answers.QID还是应该单独设置它?而且我希望Answers.AID增加到4(多选题有4个选项)。 像这样:

Answers Table                         
 AID | QID | Answer
 1 | 1 | Scripting Language
 2 | 1 | Programming Language
 3 | 1 | MarkUp Language
 4 | 1 | Network Protocol

Question Table
 QID | Question
 1 | What is HTML?

因此,每当我尝试在Answer表中插入答案时,都应检查Question.QID = Answers.QID。如果为true,则从1到4分配Answer.AID并输入答案。

所有这些都由管理员管理,所以我创建了一个Web表单AddQuestion.aspx,当管理员点击“添加”按钮时,可以添加问题,然后重定向到AddAnswer.aspx,管理员可以在其中保存并上传答案。 / p>

AddQuestion.aspx

public partial class AddQuestion : System.Web.UI.Page
{
    SqlCommand command;
    SqlConnection connection;
    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TheQuizConnectionString"].ConnectionString);
        connection.Open();

        string addQuestion = "insert into Question(Question) values(@Ques)";
        command = new SqlCommand(addQuestion, connection);

        //command.Parameters.AddWithValue("@Qid", TextBoxQid.Text);
        command.Parameters.AddWithValue("@Ques", TextBoxQuestion.Text);
        command.ExecuteNonQuery();

        Response.Redirect("AddAnswer.aspx");

        connection.Close();
    }
}

AddAnswer.aspx

public partial class AddAnswer : System.Web.UI.Page
{
     SqlCommand command;
     SqlConnection connection;
     protected void ButtonAdd_Click(object sender, EventArgs e)
     {

        Response.Redirect("AddQuestion.aspx");
     }
     public void CheckQid()
    {
        connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TheQuizConnectionString"].ConnectionString);
        connection.Open();

        string checkQid = "select count(QID) from Question";
        using (command = new SqlCommand(checkQid, connection))

    }
    protected void ButtonSave_Click(object sender, EventArgs e)
    {
        connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TheQuizConnectionString"].ConnectionString);
        connection.Open();

        string addAnswer = "insert into Answers(Answer) values(@Answer)";
        command = new SqlCommand(addAnswer, connection);

        //command.Parameters.AddWithValue("@Aid", TextBoxAid.Text);
        //command.Parameters.AddWithValue("@Qid", TextBoxQid.Text);
        command.Parameters.AddWithValue("@Answer", TextBoxAnswer.Text);

        command.ExecuteNonQuery();
        Response.Redirect("AddAnswer.aspx");
    }
}

我是asp.net和visual studio的新手。我试图寻找答案,但找不到任何东西。如果有人能帮助我,我感激不尽。

感谢。

1 个答案:

答案 0 :(得分:0)

如果AID限制为1-4,则AID不能成为主键。一种选择是使其成为由QID和AID组成的复合密钥。另一种选择是将标识列添加为主键,或者不添加标识列。

如果这是我的项目,我可能只是将新IDENTITY列上的PK添加到答案表中。请注意,我通常不进行需要对INSERT / UPDATE进行约束检查的表设计,因此没有FK,除PK外,所有字段都允许 null 。唯一的例外是如果我使用复合索引。

CREATE TABLE [dbo].[Answers] (
    AnswerNDX       INT IDENTITY(1,1) NOT NULL,
    [AID]           INT               NULL,
    [QID]           INT               NULL,
    [Answer]        NVARCHAR (200)    NULL,
    [CorrectAnswer] NVARCHAR (200)    NULL,
    CONSTRAINT PK_Answers_NDX PRIMARY KEY CLUSTERED ([AnswerNDX] ASC) ON [PRIMARY]
)

我通常会将Answer Insert例程放入存储过程中。此过程的第一部分为您的AID默认声明一个变量1.然后检查此问题是否已经有答案,如果是,则获取Max for AID并将其加1。然后它将插入新答案

CREATE PROCEDURE dbo.usp_QuestionAnswerAdd (
    @qID            INT,
    @Answer         NVARCHAR(200),
    @CorrectAnswer  NVARCHAR(200)
) AS 
BEGIN
    DECLARE @aID INT = 1
    IF EXISTS (SELECT [AID] FROM Answers WHERE (QID = @QID)) BEGIN
        SELECT @aID = Max(AID) + 1 FROM Answers WHERE (QID = @QID)
    END

    INSERT Answers( aID,  qID,  Answer,  CorrectAnswer)
    VALUES        (@aID, @Qid, @Answer, @CorrectAnswer)
END
GO

此过程的C#代码会有所不同,因为我们将调用存储过程而不是仅传递文本命令。您不会分配AID,因为SQL会查找增量。

protected void ButtonSave_Click(object sender, EventArgs e) {
    int RowsAffected;
    string connstring = ConfigurationManager.ConnectionStrings["TheQuizConnectionString"].ConnectionString;

    using (SqlConnection connection = new SqlConnection(connstring)) {
        string sqlcmd = "usp_QuestionAnswerAddusp_QuestionAnswerAdd";
        SqlCommand cmd = new SqlCommand(sqlcmd, connection);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Paramaters.AddWithValue("@qID", (int)TTextBoxQid.Text);
        cmd.Paramaters.AddWithValue("@Answer", TextBoxAnswer.Text);
        cmd.Paramaters.AddWithValue("@CorrectAnswer", string.Empty); // didnt see a value for this
        try {
            connection.Open();
            RowsAffected = cmd.ExecuteNonQuery();
        }
        catch (Exception ex) {
            RowsAffected = -1;
            // add error handling
        }
        finally { connection.Close(); }
    }
    /*
        RowsAffected should be equal to 1.
        -1 would mean there was an C# exception
        Any other failure would be in SQL commands
    */


    Response.Redirect("AddAnswer.aspx");
}    

这绝不是一个完整的例子。如果您要删除问题,AID将不会自动反映。或者,如果您想更改答案的顺序,因为AID也可以加倍ORDER BY因子。