Hi nedash,
Refer below code.
Namespaces
C#
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Text
Code
C#
string primaryKey, updateqry, TableName = "Customers";
string updateAdd = "";
protected void Page_Load(object sender, EventArgs e)
{
GenerateScript();
}
public void GenerateScript()
{
string values, IDValues = "", insqry, upqry;
int i = 0;
SqlDataReader myReader;
SqlConnection mySqlConnection = new SqlConnection();
SqlConnection mSqlConnection = new SqlConnection();
SqlCommand mySqlCommand = new SqlCommand();
SqlCommand msqlCommand = new SqlCommand();
string cnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
mSqlConnection = new SqlConnection(cnString);
mySqlConnection = new SqlConnection(cnString);
mySqlCommand = new SqlCommand("select * from Customers", mySqlConnection);
primaryKey = GetprimaryKey(TableName, cnString);
insqry = "";
mySqlConnection.Open();
if (File.Exists(Server.MapPath("~/Test.sql")))
{
File.Delete(Server.MapPath("~/Test.sql"));
}
myReader = mySqlCommand.ExecuteReader();
if (myReader != null)
{
while (myReader.Read())
{
// i this variable counts the total number of record
i = i + 1;// once a query is written, next it is available
// should be empty to build query again
updateAdd = "";
insqry = "";
string celldata = "", coulmenName = "";
for (int j = 0; j < myReader.FieldCount; j++)
{
// this empty at each reader to assign new values
// celldata contains data or value of field Like (1,Idrees)
// coulmen contain the Name of Cell Like ID,Name
if (j > 0)
{
// this condition is used for ","
//in insert and update query
{
coulmenName += "," + myReader.GetName(j).ToString();
celldata += ",'" + myReader[j].ToString() + "'";
}
}
else
{
coulmenName += myReader.GetName(j).ToString();
celldata += "'" + myReader[j].ToString() + "'";
}
if (primaryKey == myReader.GetName(j).ToString())
{
IDValues = myReader[j].ToString();
}
if (IDValues != null)
{
//Generates the update Query
upqry = UpdateQuery(coulmenName, celldata, primaryKey, IDValues);
updateAdd += upqry;
//Generates the Insert Query
insqry = InsertQuery(coulmenName, celldata, TableName);
}
}
WriteScripts(TableName, insqry, updateAdd, IDValues, primaryKey, i);
}
}
}
public string GetprimaryKey(string tableName, string cnnString)
{
string names, ID = "";
SqlDataReader mReader;
SqlConnection mSqlConnection = new SqlConnection();
SqlCommand mSqlCommand = new SqlCommand();
string cnString = cnnString;
mSqlConnection = new SqlConnection(cnString);
mSqlConnection.Open();
mSqlCommand = new SqlCommand("sp_pkeys", mSqlConnection);
mSqlCommand.CommandType = CommandType.StoredProcedure;
mSqlCommand.Parameters.Add("@table_name", SqlDbType.NVarChar).Value = tableName;
mReader = mSqlCommand.ExecuteReader();
while (mReader.Read())
{
// the primary key column reside at 4 index
ID = mReader[3].ToString();
}
return ID;
}
public void WriteScripts(string tableName, string insertqry, string updateqry, string IDvalues, string PrimaryKey, int i)
{
string script = "";
updateqry = "UPDATE " + tableName + " SET " + updateqry + " WHERE " + PrimaryKey + " = ' " + IDvalues + "'";
int index = updateqry.LastIndexOf(",");
string updatqry = updateqry.Remove(index, 1);
if (i == 1)
{
script += "DECLARE @updateCount INT;" + Environment.NewLine;
script += "DECLARE @insertCount INT;" + Environment.NewLine;
script += "DECLARE @count INT;" + Environment.NewLine;
script += " SET @updateCount = 0;" + Environment.NewLine;
script += " SET @insertCount = 0;" + Environment.NewLine;
script += "SELECT @count = COUNT(*) FROM [" + tableName + "] WHERE [" + PrimaryKey + "] = '" + IDvalues + "'" + Environment.NewLine;
script += "IF @count = 0" + Environment.NewLine;
script += "BEGIN " + Environment.NewLine;
script += "SET IDENTITY_INSERT " + tableName + " ON" + Environment.NewLine;
script += insertqry + " " + Environment.NewLine;
script += "SET IDENTITY_INSERT " + tableName + " OFF" + Environment.NewLine;
script += " SET @insertCount = @insertCount + 1 " + Environment.NewLine;
script += "END" + Environment.NewLine;
script += "ELSE" + Environment.NewLine;
script += "BEGIN" + Environment.NewLine;
script += updatqry + "" + Environment.NewLine;
script += " SET @updateCount = @updateCount + 1 " + Environment.NewLine;
script += "END" + Environment.NewLine;
StreamWriter sw = new StreamWriter(Server.MapPath("~/Test.sql"), true, Encoding.UTF8);
sw.Write(script);
sw.Close();
}
else
{
script += "SELECT @count = COUNT(*) FROM [" + tableName + "] WHERE [" + PrimaryKey + "] = '" + IDvalues + "'" + Environment.NewLine;
script += "IF @count = 0" + Environment.NewLine;
script += "BEGIN " + Environment.NewLine;
script += "SET IDENTITY_INSERT " + tableName + " ON" + Environment.NewLine;
script += insertqry + "" + Environment.NewLine;
script += "SET IDENTITY_INSERT " + tableName + " OFF" + Environment.NewLine;
script += "SET @insertCount = @insertCount + 1 " + Environment.NewLine;
script += "END" + Environment.NewLine;
script += "ELSE" + Environment.NewLine;
script += "BEGIN " + Environment.NewLine;
script += updatqry + "" + Environment.NewLine;
script += "SET @updateCount = @updateCount + 1 " + Environment.NewLine;
script += "END" + Environment.NewLine;
StreamWriter sw = new StreamWriter(Server.MapPath("~/Test.sql"), true, Encoding.UTF8);
sw.Write(script);
sw.Close();
}
}
public string InsertQuery(string coulmenName, string celldata, string TableName)
{
return "INSERT INTO " + TableName + " (" + coulmenName + ") VALUES (" + celldata + ")";
}
public string UpdateQuery(string coulmenName, string celldata, string Name, string Value)
{
string IDName, IDValue, Ud = "", name = "", values = "";
IDName = Name;
IDValue = Value;
if (IDName != null)
{
int indexcolumn = coulmenName.LastIndexOf(",");
int indexValues = celldata.LastIndexOf(",");
if (indexcolumn > 0 && indexValues > 0)
{
coulmenName = coulmenName.Substring(indexcolumn);
celldata = celldata.Substring(indexValues);
name = coulmenName.Replace(",", "");
values = celldata.Replace(",", "");
if (name != IDName && values != IDValue)
{
Ud = name + "=" + values + ",";
}
}
else
{
name = coulmenName;
values = celldata;
if (name != IDName && values != IDValue)
{
Ud = name + "=" + values + ",";
}
}
}
return Ud;
}
VB.Net
Private primaryKey, updateqry As String, TableName As String = "Customers"
Private updateAdd As String = ""
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
GenerateScript()
End Sub
Public Sub GenerateScript()
Dim values, insqry, upqry As String, IDValues As String = ""
Dim i As Integer = 0
Dim myReader As SqlDataReader
Dim mySqlConnection As SqlConnection = New SqlConnection()
Dim mSqlConnection As SqlConnection = New SqlConnection()
Dim mySqlCommand As SqlCommand = New SqlCommand()
Dim msqlCommand As SqlCommand = New SqlCommand()
Dim cnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
mSqlConnection = New SqlConnection(cnString)
mySqlConnection = New SqlConnection(cnString)
mySqlCommand = New SqlCommand("select * from Customers", mySqlConnection)
primaryKey = GetprimaryKey(TableName, cnString)
insqry = ""
mySqlConnection.Open()
If File.Exists(Server.MapPath("~/Test.sql")) Then
File.Delete(Server.MapPath("~/Test.sql"))
End If
myReader = mySqlCommand.ExecuteReader()
If myReader IsNot Nothing Then
While myReader.Read()
i = i + 1
updateAdd = ""
insqry = ""
Dim celldata As String = "", coulmenName As String = ""
For j As Integer = 0 To myReader.FieldCount - 1
If j > 0 Then
If True Then
coulmenName += "," & myReader.GetName(j).ToString()
celldata += ",'" & myReader(j).ToString() & "'"
End If
Else
coulmenName += myReader.GetName(j).ToString()
celldata += "'" & myReader(j).ToString() & "'"
End If
If primaryKey = myReader.GetName(j).ToString() Then
IDValues = myReader(j).ToString()
End If
If IDValues IsNot Nothing Then
upqry = UpdateQuery(coulmenName, celldata, primaryKey, IDValues)
updateAdd += upqry
insqry = InsertQuery(coulmenName, celldata, TableName)
End If
Next
WriteScripts(TableName, insqry, updateAdd, IDValues, primaryKey, i)
End While
End If
End Sub
Public Function GetprimaryKey(ByVal tableName As String, ByVal cnnString As String) As String
Dim names As String, ID As String = ""
Dim mReader As SqlDataReader
Dim mSqlConnection As SqlConnection = New SqlConnection()
Dim mSqlCommand As SqlCommand = New SqlCommand()
Dim cnString As String = cnnString
mSqlConnection = New SqlConnection(cnString)
mSqlConnection.Open()
mSqlCommand = New SqlCommand("sp_pkeys", mSqlConnection)
mSqlCommand.CommandType = CommandType.StoredProcedure
mSqlCommand.Parameters.Add("@table_name", SqlDbType.NVarChar).Value = tableName
mReader = mSqlCommand.ExecuteReader()
While mReader.Read()
ID = mReader(3).ToString()
End While
Return ID
End Function
Public Sub WriteScripts(ByVal tableName As String, ByVal insertqry As String, ByVal updateqry As String, ByVal IDvalues As String, ByVal PrimaryKey As String, ByVal i As Integer)
Dim script As String = ""
updateqry = "UPDATE " & tableName & " SET " & updateqry & " WHERE " & PrimaryKey & " = ' " & IDvalues & "'"
Dim index As Integer = updateqry.LastIndexOf(",")
Dim updatqry As String = updateqry.Remove(index, 1)
If i = 1 Then
script += "DECLARE @updateCount INT;" & Environment.NewLine
script += "DECLARE @insertCount INT;" & Environment.NewLine
script += "DECLARE @count INT;" & Environment.NewLine
script += " SET @updateCount = 0;" & Environment.NewLine
script += " SET @insertCount = 0;" & Environment.NewLine
script += "SELECT @count = COUNT(*) FROM [" & tableName & "] WHERE [" & PrimaryKey & "] = '" & IDvalues & "'" & Environment.NewLine
script += "IF @count = 0" & Environment.NewLine
script += "BEGIN " & Environment.NewLine
script += "SET IDENTITY_INSERT " & tableName & " ON" & Environment.NewLine
script += insertqry & " " & Environment.NewLine
script += "SET IDENTITY_INSERT " & tableName & " OFF" & Environment.NewLine
script += " SET @insertCount = @insertCount + 1 " & Environment.NewLine
script += "END" & Environment.NewLine
script += "ELSE" & Environment.NewLine
script += "BEGIN" & Environment.NewLine
script += updatqry & "" & Environment.NewLine
script += " SET @updateCount = @updateCount + 1 " & Environment.NewLine
script += "END" & Environment.NewLine
Dim sw As StreamWriter = New StreamWriter(Server.MapPath("~/Test.sql"), True, Encoding.UTF8)
sw.Write(script)
sw.Close()
Else
script += "SELECT @count = COUNT(*) FROM [" & tableName & "] WHERE [" & PrimaryKey & "] = '" & IDvalues & "'" & Environment.NewLine
script += "IF @count = 0" & Environment.NewLine
script += "BEGIN " & Environment.NewLine
script += "SET IDENTITY_INSERT " & tableName & " ON" & Environment.NewLine
script += insertqry & "" & Environment.NewLine
script += "SET IDENTITY_INSERT " & tableName & " OFF" & Environment.NewLine
script += "SET @insertCount = @insertCount + 1 " & Environment.NewLine
script += "END" & Environment.NewLine
script += "ELSE" & Environment.NewLine
script += "BEGIN " & Environment.NewLine
script += updatqry & "" & Environment.NewLine
script += "SET @updateCount = @updateCount + 1 " & Environment.NewLine
script += "END" & Environment.NewLine
Dim sw As StreamWriter = New StreamWriter(Server.MapPath("~/Test.sql"), True, Encoding.UTF8)
sw.Write(script)
sw.Close()
End If
End Sub
Public Function InsertQuery(ByVal coulmenName As String, ByVal celldata As String, ByVal TableName As String) As String
Return "INSERT INTO " & TableName & " (" & coulmenName & ") VALUES (" & celldata & ")"
End Function
Public Function UpdateQuery(ByVal coulmenName As String, ByVal celldata As String, ByVal Name As String, ByVal Value As String) As String
Dim IDName, IDValue As String, Ud As String = "", name1 As String = "", values As String = ""
IDName = name1
IDValue = Value
If IDName IsNot Nothing Then
Dim indexcolumn As Integer = coulmenName.LastIndexOf(",")
Dim indexValues As Integer = celldata.LastIndexOf(",")
If indexcolumn > 0 AndAlso indexValues > 0 Then
coulmenName = coulmenName.Substring(indexcolumn)
celldata = celldata.Substring(indexValues)
name1 = coulmenName.Replace(",", "")
values = celldata.Replace(",", "")
If name1 <> IDName AndAlso values <> IDValue Then
Ud = name1 & "=" & values & ","
End If
Else
name1 = coulmenName
values = celldata
If name1 <> IDName AndAlso values <> IDValue Then
Ud = name1 & "=" & values & ","
End If
End If
End If
Return Ud
End Function