Link to home
Start Free TrialLog in
Avatar of Varshini S
Varshini S

asked on

Dynamically create stored procedure using c#

I have the following  input parameters  in c#
string TableName , string[] PrimaryKeyColumns. Based on this parameter i need to create a stored procedure Dynamically using c#.  Stored procedure using MERGE command to update or insert record in target table.

Here SOURCE table is a temp table (#TableName )

How to achieve this in C# ?

Below is the sample stored procedure. This stored procedure needs to be created Dynamically using c#

CREATE PROC  usp_+TableName
AS
BEGIN

    MERGE MYDB.dbo.TableName
    USING  #TableName ON SOURCE.PrimaryKeyColumn1=TARGET.PrimaryKeyColumn1 AND SOURCE.PrimaryKeyColumn2=TARGET.PrimaryKeyColumn2

    WHEN MATCHED THEN

        UPDATE Set Target.column3=Source.column3,Target.column4=Source.column4

        -- UPDATE
    WHEN NOT MATCHED THEN

        INSERT(column1,column2,column3,column4)
        VALUES(SOURCE.column1,SOURCE.column2,SOURCE.column3,SOURCE.column4);

   
END
ASKER CERTIFIED SOLUTION
Avatar of Pawan Kumar
Pawan Kumar
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ste5an
Dynamically? This makes no sense... what is your use-case?
Avatar of Varshini S
Varshini S

ASKER

Use-case

I have two databases DB1  and DB2.  When i pass the table name and Primarykey columns to my C# application that will insert or update the records in  DB2 table using MERGE command.
Both DB1 and DB2 table schemas are same.   When new columns added in table the c# application drop the existing stored procedure and create  the new stored procedure with new column mappings.

Another function in my c# application will execute that stored procedure.
Are you using Entity Framework with code first approach to create these tables and store proc's in the first place? If that is the case then you should be able to drop and create new tables if there is any change in the model by using
Database.SetInitilizer(new DropCreateDatabaseIfModelchanges<dbcontext>); 

Open in new window

in global.asax.cs file inside application start.

Build Storeproc using Entity framework.
I'm not using entity frame work. Is it possible to create a stored procedure without using
Entity Framework in c#?
Yes what ever you want to do all can be handled in a single stored procedure.
Okay. Is it possible to do that using c# ? Create stored procedure using c#
What happens when the new column is part of the primary key?
New primary key column will be added in the string[] PrimaryKeyColumns.