Click here to Skip to main content
15,888,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I am facing some problem in passing data table parameter to stored procedure.

There are two table
tblQuestion and tblAnswerChoice

1. tblQuestion is for storing questions and its columns are
a)Qid int primary key identity
b)Question ntext
c)Createiondate datetime

2. tblAnswerChoice is for storing Answer Choices for the particular question and its columns are
a)Ansid int primary key identity
b)qid int
c)AnswerChoice ntext

User is free to add any number of answer choice but he must add a minimum of two.

Below is the code I am using to store the data in the database

protected void btnSubmit_Click(object sender, EventArgs e)
    {
                DataTable dataTable = new DataTable("SampleDataType");
        //we create column names as per the type in DB
        dataTable.Columns.Add("AnswerChoice", typeof(string));

        if (Session["Panel"] != null)
        {
            for (int i = 1; i <= count; i++)
            {
                if (Request.Form["txtChoice" + i] != string.Empty)
                {
                    dataTable.Rows.Add(Request.Form["txtChoice_" + i]);                }
            }
        }

        conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
        cmd = new SqlCommand();
        cmd.Connection = conn;
        
        cmd.CommandText = "sp_save_user_quiz_questions";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@Question", txtQuestion.Text);
        cmd.Parameters.AddWithValue("@CreationDate", DateTime.Now);
        cmd.Parameters.AddWithValue("@AnswerChoice1", txtChoice1.Text);
        cmd.Parameters.AddWithValue("@AnswerChoice2", txtChoice2.Text);

        SqlParameter parameter = new SqlParameter();
        //The parameter for the SP must be of SqlDbType.Structured
        parameter.ParameterName = "@Sample";
        parameter.SqlDbType = System.Data.SqlDbType.Structured;
        parameter.Value = dataTable;
        cmd.Parameters.Add(parameter);     
      
        if (conn.State == ConnectionState.Closed)
        {
            conn.Open();
        }
        try
        {
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {

        }
        cmd.Dispose();
        if (conn.State == ConnectionState.Open)
        {
            conn.Close();
        }
}

Now about the problem
I stored the answerchoices created by dynamic text box in data table. And I am passing the data table as a parameter to stored procedure.
But I am facing the problem in writing stored procedure to store the data which are is the data table. I am using SQL Server 2008. As I checked in Google my problem can be solved by Table data type. But how can I use this to solve my problem?
And one thing to note is that the qid which is generated during saving the data in tblQuestion is stored in tblAnswerChoice. So we have to fire queries for both table at one time in stored procedure.
Because at the same time data is stored in both table.

Thanks,
Deepak


[Edited]Code is wrapped in "pre" tag[/Edited]
Posted
Updated 8-Oct-11 11:48am
v4
Comments
theanil 8-Oct-11 15:03pm    
Provide stored procedure.
Bala Selvanayagam 8-Oct-11 18:37pm    
What do you expect you system to do

1. You want to save new questions and answer chocies generated in the front end ? multiple questions and each questions (tblQuestion) can have multiple answers (tblAnswerChoice) ? If so what value needs to go into "AnswerChoice" fild ? give an example

2.Do you want to save the outcom when some one answers to an another table which you have not listed here.

Can you give us an example and explain what you are trying to do please ?

1 solution

Here the solution

1. Create a type for tblQuestion in the database

SQL
CREATE TYPE [dbo].[tblQuestionType] AS TABLE(
    [question] ntext NULL,
    [creationdate] datetime NULL
)



2.Create a type for the tblAnswerChoice in the database

SQL
create TYPE [dbo].[tblAnswerChoiceType] AS TABLE(
    [answerchoice] ntext NULL
)



3.Create a stored procedure to accept two table type parameters

SQL
create procedure [dbo].[spInsert] @dtquestion tblQuestionType READONLY,@dtanswerchoice tblAnswerChoiceType READONLY as
Begin
INSERT INTO [tblQuestion]
           ([question]
           ,[creationdate])
    select [question],[creationdate] from @dtquestion

     insert into tblAnswerChoice
     (QID,AnswerChoice)
     select @@IDENTITY,answerchoice
     from @dtanswerchoice
End
GO



4.Now, your front end should be

private void button1_Click(object sender, EventArgs e)
      {
          try
          {
              //CREATE A DATA TABLE FOR TBLQUETION AND POPULATE
              DataTable odtQuestion = new DataTable();
              odtQuestion.Columns.Add("qestion");
              odtQuestion.Columns.Add("creationdate",typeof(DateTime));
              odtQuestion.Rows.Add("Quesion A", dateTimePicker1.Value);



              //CREATE A DATA TABLE FOR TBLQUETION AND POPULATE
              DataTable odtAnswerChoice = new DataTable();
              odtAnswerChoice.Columns.Add("answerchoice");
              odtAnswerChoice.Rows.Add("Choice 1");
              odtAnswerChoice.Rows.Add("Choice 2");
              odtAnswerChoice.Rows.Add("Choice 3");


              SqlConnection oConn = new SqlConnection();
              oConn.ConnectionString = "Data Source=SOLAP;database=Sample;user=sa;password=admin1990";
              oConn.Open();

              SqlCommand oCmd = oConn.CreateCommand();
              oCmd.CommandType = CommandType.StoredProcedure;
              oCmd.CommandText = "SpInsert";
              oCmd.Parameters.AddWithValue("@dtquestion", odtQuestion);
              oCmd.Parameters.AddWithValue("@dtanswerchoice", odtAnswerChoice);

              oCmd.ExecuteNonQuery();
              MessageBox.Show("Suceess");

          }
          catch (Exception ex)
          {

              MessageBox.Show(ex.Message);
          }
      }



I have tested this and it inserts tblquestion (hope its one row all the time) and the correspoding record into tblAnswerChoice.

Please note that the @@identity will have the last autonumber inserted into tblQuestion and hence its used in the tblAnswerChoice.

Also, you have to add a datetimepicker to the front end and i have used the value of it for the creation date

Hope this resolves you issue.

Bala
 
Share this answer
 
v4
Comments
aryan2010 9-Oct-11 6:23am    
First of all thanks for the giving the solution.
I have another query regarding the table datatype
How to write the stored procedure to update the data using table datatype.
Is is possible to use table datatype for updating the tblAnswerChoice
Bala Selvanayagam 9-Oct-11 6:54am    
You type should be

CREATE TYPE [dbo].[tblAnswerChoiceTypeUpdate] AS TABLE(
[AnsID] int,
[answerchoice] [ntext] NULL
)


The stored procedure should be

CREATE procedure [dbo].[spUpdateAnswerChoice] @dtanswerchoice tblAnswerChoiceTypeUpdate READONLY as
Begin

update tblAnswerChoice
set AnswerChoice=@dtanswerchoice.answerchoice
from tblAnswerChoice,@dtanswerchoice
where tblAnswerChoice.AnsID=@dtanswerchoice.AnsID

End


Hope this helps

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900