You must Sign In to post a response.
  • Category: .NET

    Have to send table name from C# to SP

    Hi friends,

    Need a SP that is common for 4 tables and have to send the table name from C# while executing.
    any idea?

    Thanks in advance
  • #764967
    it is simple, just use parameter in stored procedure as follows,
    //create stored procedure first
    CREATE PROCEDURE [dbo].[InsertUser] (
    @Username varchar(50), @Password varchar(50)
    AS INSERT INTO @Users varchar(20) VALUES(@Username, @Password)

    //call it from C#
    string username = Username.Text // get username from user string //
    password = Password.Text // get password from user
    SqlConnection conn = new SqlConnection"
    DataSource=localhost;Database=db_First;Integrated Security=SSPI");
    SqlCommand command = new SqlCommand("InsertUser", conn);
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add("@users", SqlDbType.VarChar).Value = "table1";
    command.Parameters.Add("@Username", SqlDbType.VarChar).Value = username;
    command.Parameters.Add("@Password", SqlDbType.VarChar).Value = password;
    conn.Open(); int rows = command.ExecuteNonQuery();

    hope it helps

    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]

  • #764969
    Here i have to change the table name alone and not the fields.

  • #764970
    You can execute the query inside the SP

    Create the SQL query dynamically in the SP as follows

    declare @sqlQuery nvarchar(max)
    declare @TableName nvarchar(max)
    set @TableName = 'mytableName'
    set @sqlQuery = 'Select * from ' + @TableName
    Exec sp_executesql @sqlQuery

    You can handle the query as above in the your SP

    By Nathan
    Direction is important than speed

  • #764977
    Use the below code to create the stored procedure which takes as input parameter the table name and returns all the selected rows from the table which is provided as input parameter.
    Miss. Jain
    Microsoft Certified Technology Specialist in .Net

  • #765006

    Just pass the tablename as input parameter, and prepare dynamic query since you are passing tablename as parameter, you can't able to execute directly. After Prepare dynamic query execute that with the required information.

    Give respect to your work, Instead of trying to impress your boss.

    Blog :

Sign In to post your comments