Hi nedash,
Refer below sample.
HTML
<asp:Button runat="server" Text="Download" OnClick="OnDownload" />
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, tableName = "Customers";
string updateAdd = "";
protected void OnDownload(object sender, EventArgs e)
{
DownloadScript();
}
public void DownloadScript()
{
string iDValues = "", insertQry, updateQry;
int i = 0;
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand("select * from Customers", con);
primaryKey = GetPrimaryKey(tableName, conString);
insertQry = "";
con.Open();
if (File.Exists(Server.MapPath("~/" + tableName + ".sql")))
{
File.Delete(Server.MapPath("~/" + tableName + ".sql"));
}
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
i = i + 1;
updateAdd = "";
insertQry = "";
string celldata = "", coulmenName = "";
for (int j = 0; j < sdr.FieldCount; j++)
{
if (j > 0)
{
coulmenName += "," + sdr.GetName(j).ToString();
celldata += ",'" + sdr[j].ToString() + "'";
}
else
{
coulmenName += sdr.GetName(j).ToString();
celldata += "'" + sdr[j].ToString() + "'";
}
if (primaryKey == sdr.GetName(j).ToString())
{
iDValues = sdr[j].ToString();
}
if (iDValues != null)
{
updateQry = UpdateQuery(coulmenName, celldata, primaryKey, iDValues);
updateAdd += updateQry;
insertQry = InsertQuery(coulmenName, celldata, tableName);
}
}
WriteScripts(tableName, insertQry, updateAdd, iDValues, primaryKey, i);
}
// Download the sql script file.
if (File.Exists(Server.MapPath("~/" + tableName + ".sql")))
{
byte[] bytes = File.ReadAllBytes(Server.MapPath("~/" + tableName + ".sql"));
File.Delete(Server.MapPath("~/" + tableName + ".sql"));
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + tableName + ".sql");
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
public string GetPrimaryKey(string tableName, string cnnString)
{
string iD = "";
SqlConnection con = new SqlConnection(cnnString);
SqlCommand cmd = new SqlCommand("sp_pkeys", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@table_name", SqlDbType.NVarChar).Value = tableName;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
iD = sdr[3].ToString();
}
con.Close();
return iD;
}
public void WriteScripts(string tableName, string insertqry, string updateQuery, string iDValues, string PrimaryKey, int i)
{
string script = "";
updateQuery = "UPDATE " + tableName + " SET " + updateQuery + " WHERE " + PrimaryKey + " = ' " + iDValues + "'";
int index = updateQuery.LastIndexOf(",");
string updatqry = updateQuery.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("~/" + tableName + ".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("~/" + tableName + ".sql"), true, Encoding.UTF8);
sw.Write(script);
sw.Close();
}
}
public string InsertQuery(string columnName, string cellData, string tableName)
{
return "INSERT INTO " + tableName + " (" + columnName + ") VALUES (" + cellData + ")";
}
public string UpdateQuery(string columnName, string cellData, string Names, string value)
{
string iDName, iDValue, ud = "", name = "", values = "";
iDName = Names;
iDValue = value;
if (iDName != null)
{
int indexcolumn = columnName.LastIndexOf(",");
int indexValues = cellData.LastIndexOf(",");
if (indexcolumn > 0 && indexValues > 0)
{
columnName = columnName.Substring(indexcolumn);
cellData = cellData.Substring(indexValues);
name = columnName.Replace(",", "");
values = cellData.Replace(",", "");
if (name != iDName && values != iDValue)
{
ud = name + "=" + values + ",";
}
}
else
{
name = columnName;
values = cellData;
if (name != iDName && values != iDValue)
{
ud = name + "=" + values + ",";
}
}
}
return ud;
}
VB.Net
Private primaryKey As String, tableName As String = "Customers"
Private updateAdd As String = ""
Protected Sub OnDownload(ByVal sender As Object, ByVal e As EventArgs)
DownloadScript()
End Sub
Public Sub DownloadScript()
Dim insertQry, updateQry As String, iDValues As String = ""
Dim i As Integer = 0
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim con As SqlConnection = New SqlConnection(conString)
Dim cmd As SqlCommand = New SqlCommand("select * from Customers", con)
primaryKey = GetPrimaryKey(tableName, conString)
insertQry = ""
con.Open()
If File.Exists(Server.MapPath("~/" & tableName & ".sql")) Then
File.Delete(Server.MapPath("~/" & tableName & ".sql"))
End If
Dim sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
i = i + 1
updateAdd = ""
insertQry = ""
Dim celldata As String = "", coulmenName As String = ""
For j As Integer = 0 To sdr.FieldCount - 1
If j > 0 Then
coulmenName += "," & sdr.GetName(j).ToString()
celldata += ",'" & sdr(j).ToString() & "'"
Else
coulmenName += sdr.GetName(j).ToString()
celldata += "'" & sdr(j).ToString() & "'"
End If
If primaryKey = sdr.GetName(j).ToString() Then
iDValues = sdr(j).ToString()
End If
If iDValues IsNot Nothing Then
updateQry = UpdateQuery(coulmenName, celldata, primaryKey, iDValues)
updateAdd += updateQry
insertQry = InsertQuery(coulmenName, celldata, tableName)
End If
Next
WriteScripts(tableName, insertQry, updateAdd, iDValues, primaryKey, i)
End While
If File.Exists(Server.MapPath("~/" & tableName & ".sql")) Then
Dim bytes As Byte() = File.ReadAllBytes(Server.MapPath("~/" & tableName & ".sql"))
File.Delete(Server.MapPath("~/" & tableName & ".sql"))
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = ContentType
Response.AppendHeader("Content-Disposition", "attachment; filename=" & tableName & ".sql")
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End If
End Sub
Public Function GetPrimaryKey(ByVal tableName As String, ByVal cnnString As String) As String
Dim iD As String = ""
Dim con As SqlConnection = New SqlConnection(cnnString)
Dim cmd As SqlCommand = New SqlCommand("sp_pkeys", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@table_name", SqlDbType.NVarChar).Value = tableName
con.Open()
Dim sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
iD = sdr(3).ToString()
End While
con.Close()
Return iD
End Function
Public Sub WriteScripts(ByVal tableName As String, ByVal insertqry As String, ByVal updateQuery As String, ByVal iDValues As String, ByVal PrimaryKey As String, ByVal i As Integer)
Dim script As String = ""
updateQuery = "UPDATE " & tableName & " SET " & updateQuery & " WHERE " & PrimaryKey & " = ' " & iDValues & "'"
Dim index As Integer = updateQuery.LastIndexOf(",")
Dim updatqry As String = updateQuery.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("~/" & tableName & ".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("~/" & tableName & ".sql"), True, Encoding.UTF8)
sw.Write(script)
sw.Close()
End If
End Sub
Public Function InsertQuery(ByVal columnName As String, ByVal cellData As String, ByVal tableName As String) As String
Return "INSERT INTO " & tableName & " (" & columnName & ") VALUES (" & cellData & ")"
End Function
Public Function UpdateQuery(ByVal columnName As String, ByVal cellData As String, ByVal Names As String, ByVal value As String) As String
Dim iDName, iDValue As String, ud As String = "", name As String = "", values As String = ""
iDName = Names
iDValue = value
If iDName IsNot Nothing Then
Dim indexcolumn As Integer = columnName.LastIndexOf(",")
Dim indexValues As Integer = cellData.LastIndexOf(",")
If indexcolumn > 0 AndAlso indexValues > 0 Then
columnName = columnName.Substring(indexcolumn)
cellData = cellData.Substring(indexValues)
name = columnName.Replace(",", "")
values = cellData.Replace(",", "")
If name <> iDName AndAlso values <> iDValue Then
ud = name & "=" & values & ","
End If
Else
name = columnName
values = cellData
If name <> iDName AndAlso values <> iDValue Then
ud = name & "=" & values & ","
End If
End If
End If
Return ud
End Function