0

I am working on a program in c# where I have a layout as shown in the image below:

The Image

The purpose of the program is to perform data archiving in SQL server. If I choose "Create Tables", it will generate new tables into my database ( should generate about 40 tables in order) which has similar table structure (columns,constraint,triggers,etc) as original tables in the same database as well. How this works is I'll execute the SQL scripts in c# and call them (all 40 scripts) to create tables.

Right now, I added another button "Transfer data" where it will select specfic data(based on date) in old data and transfer them into the new tables I created. I will use the query Insert Into....SELECT from to transfer data.

My question is should I create sql scripts for transferring data and execute them in c# or just put the SQL queries inside my c# code ?

If I go with SQL scripts, should I split them into 40 scripts as well or place all the queries inside 1 script? I know it will be tedious if i put everything in one script as if an error occurs, it's hard to trace the source of the problem.

Below is a sample of how the sql query looks like :

SET IDENTITY_INSERT Kiosk_Log_New ON
INSERT INTO Kiosk_Log_New(LOGID,
                          logAPPID,
                          logLOGTID,
                          logGUID,
                          logOriginator,
                          logReference,
                          logAssemblyName,
                          logFunctionName,
                          logMessage,
                          logException,
                          CreatedBy,
                          CreatedDate)
SELECT                  LOGID,
                          logAPPID,
                          logLOGTID,
                          logGUID,
                          logOriginator,
                          logReference,
                          logAssemblyName,
                          logFunctionName,
                          logMessage,
                          logException,
                          CreatedBy,
                          CreatedDate FROM Kiosk_Log
WHERE CreatedDate BETWEEN '2015-01-01' AND GETDATE()

EDIT: Since many suggested stored procedure is the best option, this would be my create tables script:

  string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        /*  open sql connection to execute SQL script: PromotionEvent_New   */
        try
        {
            using (SqlConnection con = new SqlConnection(constr))
            {
                con.Open();
                FileInfo file = new FileInfo("C:\\Users\\88106221\\Documents\\SQL Server Management Studio\\PromotionEvent_New.sql");
                string script = file.OpenText().ReadToEnd();
                Server server = new Server(new ServerConnection(con));
                server.ConnectionContext.ExecuteNonQuery(script);
                Display("PromotionEvent_New table has been created successfully");
                con.Close();



            }

        }
        catch(Exception ex)
        {

            textBox1.AppendText(string.Format("{0}", Environment.NewLine));
            textBox1.AppendText(string.Format("{0} MainPage_Load() exception - {1}{2}", _strThisAppName, ex.Message, Environment.NewLine));
            Display(ex.Message + "PromotionEvent_New could not be created");
            textBox1.AppendText(string.Format("{0}", Environment.NewLine));
            Debug.WriteLine(string.Format("{0} MainPage_Load() exception - {1}", _strThisAppName, ex.Message));


        }
toha
  • 5,095
  • 4
  • 40
  • 52
Cookie Monster
  • 636
  • 1
  • 12
  • 29

2 Answers2

2

It's best to use a stored procedure with a transaction to execute all your INSERT queries.

It's not advisable to submit queries from your C# code as explained in last post by John Ephraim Tugado due to a number of reasons; the most important reasons being,

  • easier maintenance of INSERT queries
  • minimal bandwidth consumption between web server and database server

Sending long queries strings from C# code will consume more bandwidth between web server and database server and could slow the database response in a high traffic scenario.

You can execute the following T-SQL code against your database to create a stored procedure for transferring/archiving data to archived tables. This procedure makes sure that all your INSERTS are executed within a transaction, that ensures you don't end up with orphaned tables and unnecessary headaches down the road.

Stored Procedure for transferring data

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Lord Cookie
-- Create date: 11/01/2017
-- Description: Transfers data to existing archived tables
-- =============================================
CREATE PROCEDURE dbo.ArchiveData

AS
BEGIN

    SET NOCOUNT ON;
    BEGIN TRY
         --use transaction when inserting data else you may end up with orphaned data and hard to debug issues later on
        BEGIN TRANSACTION

        --add your INSERT queries one after the other below
        SET IDENTITY_INSERT Kiosk_Log_New ON
        INSERT INTO Kiosk_Log_New (LOGID,
        logAPPID,
        logLOGTID,
        logGUID,
        logOriginator,
        logReference,
        logAssemblyName,
        logFunctionName,
        logMessage,
        logException,
        CreatedBy,
        CreatedDate)
                SELECT
                    LOGID
                    ,logAPPID
                    ,logLOGTID
                    ,logGUID
                    ,logOriginator
                    ,logReference
                    ,logAssemblyName
                    ,logFunctionName
                    ,logMessage
                    ,logException
                    ,CreatedBy
                    ,CreatedDate
                FROM Kiosk_Log
                WHERE CreatedDate BETWEEN '2015-01-01' AND GETDATE()

        --add more of your insert queries below


        -- finally commit transaction
        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        DECLARE @errorDetails NVARCHAR(MAX);
        set @errorDetails = 'Error ' + CONVERT(VARCHAR(50), ERROR_NUMBER()) +
        ', Severity ' + CONVERT(VARCHAR(5), ERROR_SEVERITY()) +
        ', State ' + CONVERT(VARCHAR(5), ERROR_STATE()) +
        ', Line ' + CONVERT(VARCHAR(5), ERROR_LINE());

          --roll back the transaction
        IF XACT_STATE() <> 0
        BEGIN
            ROLLBACK TRANSACTION
        END

        --you can log the above error message and/or re-throw the error so your C# code will see an error
        --but do this only after rolling back
    END CATCH;
END
GO

You can then call the above stored procedure using C# as shown in sample code below.

Call above stored procedure using C#

using(SqlConnection sqlConn = new SqlConnection("Your database Connection String")) {
 using(SqlCommand cmd = new SqlCommand()) {
  cmd.CommandText = "dbo.ArchiveData";
  cmd.CommandType = CommandType.StoredProcedure;
  cmd.Connection = sqlConn;
  sqlConn.Open();
  cmd.ExecuteNonQuery();
 }
}
Sunil
  • 20,653
  • 28
  • 112
  • 197
  • What about for creating tables? Should i create stored procedures as well for them? – Cookie Monster Nov 01 '17 at 06:07
  • Or it is better to create separate stored procedure for each table insertion or dump them all in 1 stored procedure? – Cookie Monster Nov 01 '17 at 06:18
  • You have to make sure that tables are already created before running transferring data. Table creation is a one-time job, so you could make sure once that they are created and then just bother about transferring data. – Sunil Nov 01 '17 at 06:24
  • Also, you could create 40 different stored procedures and call each of them from the above stored procedure. That is another option. It will make your stored procedure smaller in size that may help to maintain them. – Sunil Nov 01 '17 at 06:25
  • Now, i have sql scripts for creation of tables in 40 scripts file. Should i put them in stored procedures? – Cookie Monster Nov 01 '17 at 06:27
  • If you create a stored procedure for creating tables, then I think it might an overkill since your tables need to be created only once for the lifetime of app. So, just create them initially before you push your C# app for archiving. – Sunil Nov 01 '17 at 06:28
  • I would just take the SQL create table scripts and run them directly in SSMS before pushing your C# app for archiving. Creating a stored procedure would be an overkill here since you are not going to repeat this often. Also, you only want the DBA to be able to create tables else it creates vulnerable points in your application. – Sunil Nov 01 '17 at 06:30
  • Even if you put all INSERT statements into one procedure you can still track the error using the `@errorDetails` variable in above stored procedure. Plus you are ensured that any error will automatically roll back all inserts, so there is no scope for confusion and headaches when an error occurs. – Sunil Nov 01 '17 at 06:33
  • I think I should explain the nature of my program so you have a clearer picture. As mentioned, the purpose of my program is for data archiving. So the process would be like i have a number of tables in my database that i want to archive. I would have to have a function(button) to create table , after that transfer data from original table to new table , after that count data to ensure right amount of data is in new table, after drop old table, and then rename clone table to old table name. This ensures in the future, if i have to do data archiving again, this program would be easy to do it. – Cookie Monster Nov 01 '17 at 06:33
  • So will the schema of your archived tables change over time? – Sunil Nov 01 '17 at 06:34
  • Well, I understand your answer but i already wrote all my sql scripts for creation tables, do i have to re-write again for stored procedure in this case? – Cookie Monster Nov 01 '17 at 06:34
  • By archieved tables, what do you mean? – Cookie Monster Nov 01 '17 at 06:35
  • By archived tables I mean the tables into which you insert data. – Sunil Nov 01 '17 at 06:36
  • Take your SQL Scripts and run them in SQL Server Management Studio against the database you want to use. – Sunil Nov 01 '17 at 06:37
  • If i understand your question correctly, say I have tableA (one of the tables i want to archive) , I will just need to create a clone table having same table structure (constraint,triggers,indexes,etc) and named it tableA_New and transfer the data i want to keep. Then drop tableA and renamed tableA_New to tableA – Cookie Monster Nov 01 '17 at 06:37
  • I did a test run on my sql scripts. All 40 scripts of them worked fine when I run them in SQL server. – Cookie Monster Nov 01 '17 at 06:38
  • So in your case the table to archive could change every time a user uses your C# app? – Sunil Nov 01 '17 at 06:39
  • And a side note: I am working this program now on a testing server. When I finished the program, it should be used on a live server (different server) with a different team using my program. – Cookie Monster Nov 01 '17 at 06:39
  • I don't understand your question very well. can you rephrase it? – Cookie Monster Nov 01 '17 at 06:40
  • I mean that today a user decides to archive table1 and tomorrow another user decides to archive table2 and day after tomorrow another user decides to archive table1 and table5. Is this how your app works? – Sunil Nov 01 '17 at 06:42
  • Look at it this way, we don't do data archiving everyday, but just once in a while. Say now, I want to transfer data newer than 2015 into "new table". Then maybe we can use the program again to transfer data newer than 2020 say in 5 years time. – Cookie Monster Nov 01 '17 at 06:42
  • oh that's not how my app works. Only one person will run this program, that's the end of story. Say I am the user, when i run it, it will just create all 40 new tables, and then transfer those datas, and etc. At the same time, I can hand my program to a live server team so they can configure it the connection string to their live server to perform the functions as well. For me now, i am just performing this program on my testing server. – Cookie Monster Nov 01 '17 at 06:44
  • So tables to archive will change very often? If not there is no point in allowing an end user to create tables in your database. Its not a good practice from security point of view. Only the database administrator should be creating new tables. – Sunil Nov 01 '17 at 06:44
  • Well my superior wants the program to be able to generate new tables. For your question, tables to archive will not change very often. It's just a one time thing you could say it. – Cookie Monster Nov 01 '17 at 06:46
  • Is my method actually wrong? Where you execute the scripts individually in c#. – Cookie Monster Nov 01 '17 at 06:48
  • Please advise because I can't think of a way to work this out. – Cookie Monster Nov 01 '17 at 06:51
  • You need to ask the database administrator if end users can create new tables in database. If he or she says yes then go ahead and run your create scripts from c#. – Sunil Nov 01 '17 at 06:58
  • Your method is not wrong. You can also execute the scripts individually. – Sunil Nov 01 '17 at 06:59
  • What if end users can't create new table? I could hand them the program along with the script files, it would work as well right? But they have to alter the c# code of the program to reference to the correct directory of each file. – Cookie Monster Nov 01 '17 at 07:01
  • Do you have a database administrator in your company? If there is none, then just use your approach as it will work, even though allowing end users to create new tables is a security risk. – Sunil Nov 01 '17 at 07:04
  • Yes there is a database admin in my company. Actually, my program has a login screen before having access to the program, i forgot to mention that. That means the login mode will have two options : Windows authentication or sql server authentication. So people who want to use the program have to be logged into their computer laptops to have access to the program or have access to the server (if they use sql server auth login). – Cookie Monster Nov 01 '17 at 07:07
  • So I don't see a security risk. – Cookie Monster Nov 01 '17 at 07:07
  • Did you ask your company's database admin? But if you don't want to ask him, then go ahead and do what you have in mind. There is no problem in running your scripts from C# code for creating tables. – Sunil Nov 01 '17 at 07:13
  • Table creation is one time job. But the thing is say I want to perform data archiving every end of the year. That would mean I have to create those tables again(with new name), transfer data i want to keep, drop original tables, rename new table to original table. So isn't that better to use stored procedure for creation table as well? – Cookie Monster Nov 01 '17 at 07:16
  • Come to think of it , you are right. What if someone modify the sql scripts , say adding drop table. Then that would be dangerous right? Using stored procedure, only users who have access to the server can make changes to the stored procedure. – Cookie Monster Nov 01 '17 at 07:18
  • Say I am going for stored procedure for creation tables, do I have to re-write stored procedure again or can i use the sql script to amend it? Also, should i create 40 stored procedure for 40 tables creation or put them all in one? – Cookie Monster Nov 01 '17 at 07:20
  • Create a separate stored procedure for creating tables. Put your create scripts into this procedure. If you want to use the same procedure for creating and transferring data then just include the scripts in the procedure I gave. – Sunil Nov 01 '17 at 07:23
  • I would create one stored procedure, else the number of procedures could multiply. With one stored procedure at least you know the exact database object one needs to change for data archiving. – Sunil Nov 01 '17 at 07:24
  • Makes sense. Could i just copy paste my sql create table script into store procedure as the syntax is same? Do you know the proper format , at least it could generate error if there is. – Cookie Monster Nov 01 '17 at 07:27
  • Yes just paste it and then test the stored procedure and debug it. – Sunil Nov 01 '17 at 07:29
  • So, 1 stored procedure for creation tables, another stored procedure for transfer data, another stored procedure for drop tables, etc etc??? – Cookie Monster Nov 01 '17 at 07:29
  • From my above queries for create table, what's the format to catch error handling ? – Cookie Monster Nov 01 '17 at 07:30
  • Yes you can do that also. But it seems dropping of tables happens after transferring data, so you could just include it in transfer data stored procedure. – Sunil Nov 01 '17 at 07:30
  • Use TRY CATCH like I have shown in the procedure in my answer to track errors. – Sunil Nov 01 '17 at 07:31
  • Does stored procedure accepts triggers,costraints ,etc as well? – Cookie Monster Nov 01 '17 at 07:34
  • The stored procedure format you posted applies on create,insert,update tables/data? If the script runs manually in SSMS, the script should run in stored procedure right? – Cookie Monster Nov 01 '17 at 07:36
  • You have to run the stored procedure from C# using the sample code I gave in my answer. Yes the stored procedure format I gave can be used for update/delete/insert statements. Yes, if running in SSMS, the simply run the stored procedure. – Sunil Nov 01 '17 at 07:41
  • You can script triggers, constraints in your CREATE TABLE statement. – Sunil Nov 01 '17 at 07:42
  • Okay I'll give it a try, perhaps i shall mark your answer as solved? – Cookie Monster Nov 01 '17 at 07:42
  • My sql scripts for create table already have everything from create table,create indexes,create triggers,constraints,etc etc. But it would be a bit long because some tables have more triggers or constraints etc. – Cookie Monster Nov 01 '17 at 07:43
  • No. It's normal sometimes to have large stored procedures. – Sunil Nov 01 '17 at 08:05
  • One more thing, how would I test my stored procedure to know it's successfully created? Say I have to create tableA_New, do i execute it once or what happens if i execute it many times? Will it overwrite the existing one? – Cookie Monster Nov 01 '17 at 08:08
  • Have a look at my code above, i got error trying to create stored procedure for just 1 table. Everything seems to check out but it throws some syntax error . – Cookie Monster Nov 01 '17 at 08:15
  • Remove lines that set ansi etc. Just have the IF statements with their query in stored procedure. You could put this in CATCH part: Select @errorDetails as ErrorDetails. If your stored runs and dooes not return error details then the procedure ran successfully. – Sunil Nov 01 '17 at 08:46
  • Running your create procedure will not recreate the tables due to the IF part. – Sunil Nov 01 '17 at 08:48
  • Remove all GO statements from the procedure body. – Sunil Nov 01 '17 at 08:49
  • Remove all set ansi.. And set quoted... Statements from within your procedure body. – Sunil Nov 01 '17 at 08:50
  • Well my supervisor doesn't want to work on stored procedure so i guess there's not much reason for this discussion anymore. – Cookie Monster Nov 01 '17 at 08:58
  • But as a token of appreciation for suggesting a possible scenario, i marked your answer and upvoted. – Cookie Monster Nov 01 '17 at 08:58
  • Then its easier for you. Just use the scripts you have from your C# code. But make sure to run your queries in the context of a transaction. – Sunil Nov 01 '17 at 09:00
  • Here is the thing: in my edited post with c# code. If i want to package my program application and send my sql scripts file to another team or user for example, they won't have access to the source code of my c# program. Meaning under the directory file for calling the scripts, they might save in another location they wish to, is there a way to package the directory so that they will be able to run the .exe to always locate the correct folder?? – Cookie Monster Nov 01 '17 at 09:02
  • You can request them to input the path to scripts folder in your app and then fetch those scripts using the path given by them. – Sunil Nov 01 '17 at 09:05
  • Can you clarify your statement because I don't follow. – Cookie Monster Nov 01 '17 at 09:05
  • What about the connection string in the app.config? Because now, my it is referenced to my testing server, when the other team uses it, they want to apply it on a live server, so different server name. How will they configure in an exe file? – Cookie Monster Nov 01 '17 at 09:08
  • You have to change the connection string in app config so it points to live database when you give your app to live users. – Sunil Nov 01 '17 at 09:09
  • I see. As for the calling the scripts in directory, I believe there is a built in function in .Net to make sure any users can call the scripts path? kinda like how when someone installs a game, it will choose the correct path folder in it. I think i need to package the SQL script folders to the .exe file when I package the app, is that correct? – Cookie Monster Nov 01 '17 at 09:11
  • In your C# app a dialog should popup asking the users path to scripts files. Path could be c:\ abc\ def\ or any other valid path. All script files are stored under this path. So you would have createTables.sql and transferData.sql under this path. – Sunil Nov 01 '17 at 09:13
  • Ya but right now one of my sql script is path : "C:\\Users\\88106221\\Documents\\SQL Server Management Studio\\PromotionEvent_New.sql") . The other user might now save the folder SQL server management studio (contains all sql scripts for create table) to other path, then this app wouldn't be able to locate the scripts. – Cookie Monster Nov 01 '17 at 09:16
  • What would you suggest to do? – Cookie Monster Nov 01 '17 at 09:17
  • Then just package it with your exe file. Look at this link on doing this https://solutioncenter.apexsql.com/how-to-package-database-scripts-into-c-projects-and-net-executables/ – Sunil Nov 01 '17 at 09:25
  • Thanks, so this solves the issue I am talking about? Also it's compatible with any version of visual studio? – Cookie Monster Nov 01 '17 at 09:28
  • It should be. Just use the same approach in your scenario. You would have to adapt it to your situation. – Sunil Nov 01 '17 at 09:41
  • Yup all should work fine but i think i will foresee an issue when using rename new table to old table in the future. Since new tables will have to use new names for constraints,triggers, etc as they can't have the same name as original table right? So after renaming table, if generate create table again, it should give an error since the new name already exists. Unless i rename all constraint,triggers etc to original names as well. – Cookie Monster Nov 01 '17 at 09:45
  • Also, if i alter table to rename, my original sql script will break, i.e it will still be the new name unless i make changes to it, is there a way to overcome this? – Cookie Monster Nov 01 '17 at 09:46
  • You will have to drop table before creating a new one. Also, look at this for embedding your script file into your exe. https://stackoverflow.com/questions/433171/how-to-embed-a-text-file-in-a-net-assembly. If object names clash then you will have to create new names. – Sunil Nov 01 '17 at 09:51
  • Problem about data archiving is that you always have to create table first then only you can drop. 1. Create new table new name 2. Transfer data want to keep 3. drop original table 4. rename new table to original table name. So if you drop table first ( where it current new one becomes original one), you can't use the program to transfer data anymore since you can't select data from original table. – Cookie Monster Nov 01 '17 at 09:54
  • You can create archived tables in a separate database and then there will never be a clash. – Sunil Nov 01 '17 at 10:02
  • Or if you have to create in same database then create the archived tables under a different schema. Then also no name clash will not occur. – Sunil Nov 01 '17 at 10:05
  • When you specify table name in your script, use following naming so schema is part of table name. archives.table1 instead of just saying table1. But you should have the schema called archives already created. The database administrator can create this schema for you. – Sunil Nov 01 '17 at 10:12
  • For transfer data script, should I put all queries for 40 tables in 1 script file or separate them in each script ? I was thinking separate because when i execute and call them in c# at least if there is an error handling, i know which script gives the error. – Cookie Monster Nov 01 '17 at 10:12
  • Yes, separate is fine. – Sunil Nov 01 '17 at 10:14
  • But that doesn't really solve the naming for constraint,triggers,etc because they have to be unique, i.e only a specific name can exist in the database. – Cookie Monster Nov 01 '17 at 10:15
  • I am really overthinking myself so badly -.- – Cookie Monster Nov 01 '17 at 10:15
  • If you use a different schema then index names etc. will NOT clash even though they might appear the same. Just make sure the new table is created in a different schema. Zero clash.... – Sunil Nov 01 '17 at 10:28
  • But i am right. Creating new tables again in the future, say for the second time, shall generate error as some of the names in original table already existed. Am i right? The triggers,constraints can't have same name even if different table names? – Cookie Monster Nov 01 '17 at 10:28
  • I can use same index name but not constraint and triggers and keys – Cookie Monster Nov 01 '17 at 10:30
  • When you create tables for second time your IF statement will check if it already exists and if it does then it will not create any new table with its associated objects. – Sunil Nov 01 '17 at 10:30
  • You can use all same names provided you are in different schema. – Sunil Nov 01 '17 at 10:30
  • Yea my main function is to always create tables that carries all the structure (constraints,keys,triggers,etc) as before in the first original table. – Cookie Monster Nov 01 '17 at 10:32
  • I see, problem is I want to keep it as original as possible so want to avoid use of different schema. – Cookie Monster Nov 01 '17 at 10:34
  • So the best possible option is to re-edit my sql scripts when I want to use the program in the future and package the exe file again?? – Cookie Monster Nov 01 '17 at 10:35
  • Unless in my rename function, i alter rename table name, constraint,triggers,etc. Also, in rename function, should i put all queries in 1 script since it's so short? – Cookie Monster Nov 01 '17 at 10:37
  • Yes. Your approach is not good but if this is what your boss wants, you have no choice. – Sunil Nov 01 '17 at 10:38
  • Also with different schemas, it's hard to transfer data from old to new. – Cookie Monster Nov 01 '17 at 10:40
  • You really have no choice after listening to your comments. You must use same database, same schema and no stored procedures. So this should become your strategy and you should solve your problem using this approach. – Sunil Nov 01 '17 at 10:40
  • Why don't they just allow use to use same names for constraints,keys,triggers in different tables but in same db? Makes life easier. – Cookie Monster Nov 01 '17 at 10:41
  • No problems with schemas when transferring data. Schemas are there for situations like this. – Sunil Nov 01 '17 at 10:41
  • Using same names is not allowed in same database and same schema. – Sunil Nov 01 '17 at 10:43
  • Just follow this approach your boss wants and start solving your problem one step at a time. Don't try to solve the whole problem in one step. So try to archive only one table and see how it goes. You will discover issues and workarounds as you write and test. – Sunil Nov 01 '17 at 10:44
  • Yea, anyway using different schemas will defeat the purpose of renaming because when we rename , we want to follow default schema name, that is dbo.TableA. Also, even if i use different schema, in the future, I still have edit the script as archives.TableA already have the same names that will be used to generate new tables again, unless I create another schema. – Cookie Monster Nov 01 '17 at 10:50
  • Thanks for the explanation, appreciate your help ! – Cookie Monster Nov 01 '17 at 10:51
  • Sure. Like I said you have no choice and you are stuck with using a bad approach to solving this problem by not following best practices of database programming. So, just accept it and start coding your solution. Wish you best of luck. – Sunil Nov 01 '17 at 10:53
  • The table creation for second and third time in archives schema will not give errors since you are using IF statement to check existence of your new table. – Sunil Nov 01 '17 at 10:54
  • Using schema or a separate archives database is the best option in your situation. – Sunil Nov 01 '17 at 11:28
  • Sure table creation for 2nd and 3rd in archives schema will not give error but it also won't generate the constraint,triggers etc I want so kinda defeat the purpose of creating the table. – Cookie Monster Nov 02 '17 at 02:26
  • Can you not drop the triggers and constraints always and recreate it everytime? – Sunil Nov 02 '17 at 03:21
  • What do you mean? Example? – Cookie Monster Nov 02 '17 at 03:23
  • Or maybe I could rename table name and those constraint and triggers as well so everything won't be affected. – Cookie Monster Nov 02 '17 at 03:23
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/158571/discussion-between-sunil-and-lord-cookie). – Sunil Nov 09 '17 at 06:04
  • I posted this thread and not solved how to tackle it : https://stackoverflow.com/questions/47469585/displaying-row-count-from-sql-server-to-program – Cookie Monster Nov 24 '17 at 09:33
1

Depending on the table naming and design, I would suggest creating a script to create a stored procedure for this that would generate one for each of your tables. I'm no expert in scripting but it is the same with the script that generates an audit trail for each of your tables or at least the ones you defined in the script.

Hard-coding this inside your c# application is a big NO as there is the possibility of database changes. We would want our app to be flexible to change with the least amount of effort.

If generating the script to create a stored procedure is hard for you, I would still recommend manually creating stored procedures for this task.

jegtugado
  • 5,081
  • 1
  • 12
  • 35
  • So your suggestion would be to write the queries in a sql scripts and call them in c# program? Rather than writing the sql queries inside the c# code? – Cookie Monster Nov 01 '17 at 04:36
  • So should create scripts for transfer data from old to new table and execute them in c# in order? why would you recommend stored procedure? I am not familiar with stored procedure to be honest. – Cookie Monster Nov 01 '17 at 04:37
  • No. You create stored procedures inside the database itself. It would be easier for the database admin to change the script as needed without changing a thing in your application. With this, the script won't rely on a developer and allow someone with knowledge of scripting to maintain it. As to why stored procedures are recommended, I believe there is sufficient material here in SO that explains the topic. – jegtugado Nov 01 '17 at 04:48
  • After creating the stored procedures in the database, you can then call the stored procedures and pass the necessary parameters inside your c# application. – jegtugado Nov 01 '17 at 04:49
  • I see. Since i already have done the scripting calling for creating tables inside my program, should I change it to stored procedure method? – Cookie Monster Nov 01 '17 at 06:05
  • Well my scripts are being executed on a testing server, if I have to run the program on a live server, will stored procedure still be the way to go? – Cookie Monster Nov 01 '17 at 06:12
  • Stored Procedures is the best way if you want a more maintainable and secure way of performing transactions. One more benefit of using stored procedures is that you could execute jobs on the database level that executes your procedures without the need of an application. Normally, cloning data from one db to another is done through jobs and not some applications since jobs can be scheduled. You'd appreciate what I'm saying if you gain enough knowledge about stored procedures and jobs in the database which is mostly for db admins. – jegtugado Nov 01 '17 at 07:12