Mike
Mike

Reputation: 257

How to create dynamic parameters in SQL Server stored procedure

I have a form that generate inputs dynamically, then I get their values and generate command parameters dynamically.

    SqlConnection con = new SqlConnection(cs);

    SqlCommand cmd =new SqlCommand("insert_op",con);
    cmd.CommandType = CommandType.StoredProcedure;

    for (int i = 0; i < Request.Form.Count; i++)
    {
        if (Request.Form["frm_option" + (i + 1)] != null)
        {

            cmd.Parameters.AddWithValue("@op" + i, Request.Form["frm_option" + (i + 1)]);
        }
    }
    try
    {
        using (con)
        {
            con.Open();
            cmd.ExecuteNonQuery();
        }
    }
    catch
    {
    }

How can I pass these dynamic parameters to SQL Server stored procedure and how should stored procedure be?

Upvotes: 0

Views: 3216

Answers (3)

Vadim Loboda
Vadim Loboda

Reputation: 3101

If you want to "insert each parameter into separate row" then perhaps it is better to use table variable as a stored prosedure parameter?

Your User Defined Table Type and stored procedure might look like:

create type dbo.ValueTableType as table (Value varchar(255))
GO

create procedure dbo.InsertValues
    @Values dbo.ValueTableType readonly
as
begin

    insert into dbo.YourTable (Value)
    select Value from @Values;
end

See this ADO.NET example of how to initialize and pass a table parameter to stored procedure https://stackoverflow.com/a/10409710/623190

Upvotes: 1

Haseeb Asif
Haseeb Asif

Reputation: 1786

First of all, this isn't the right design.

To achieve your goal you need to pass multiple values in SQL statment as follows

SQL

INSERT INTO tbl_options(op_name) VALUES (value1),(value2),...(nthValue)

Code

Your code will be something like this

string command = "INSERT INTO tbl_options(op_name) VALUES";    
for (int i = 0; i < Request.Form.Count; i++)
                {                      
                    if (Request.Form["frm_option" + (i + 1)] != null)
                    {
                        command += "(@op" + i + "),";

                        cmd.Parameters.AddWithValue("@op" + i, Request.Form["frm_option" + (i + 1)]);
                    }
                }

Upvotes: 2

Crowcoder
Crowcoder

Reputation: 11514

You can provide defaults for every field in the table, so any parameters you do not pass in will get the default. Here I demonstrate defaults of NULL.

CREATE PROCEDURE [dbo].[sproc_tbl_options_Insert] 
    @op_name nvarchar(50) = NULL,
    @op_somethingelse nvarchar(5) = NULL,
    @op_number int = NULL
AS
BEGIN
    INSERT INTO [tbl_options] (op_name, op_somethingelse, op_number)
    VALUES (@op_name, @op_somethingelse, @op_number);
END

Upvotes: 1

Related Questions