2753 lines
152 KiB
C#
2753 lines
152 KiB
C#
|
using System;
|
|||
|
using System.Collections.Generic;
|
|||
|
using System.ComponentModel;
|
|||
|
using System.Data;
|
|||
|
using System.Data.SqlClient;
|
|||
|
using System.Drawing;
|
|||
|
using System.Linq;
|
|||
|
using System.Text;
|
|||
|
using System.Threading.Tasks;
|
|||
|
using System.Windows.Forms;
|
|||
|
using System.IO;
|
|||
|
using System.Reflection;
|
|||
|
|
|||
|
namespace DatabaseComparison
|
|||
|
{
|
|||
|
public partial class Form1 : Form
|
|||
|
{
|
|||
|
StringBuilder _sbErrMsg = new StringBuilder();
|
|||
|
List<TableList> _oTableLists = new List<TableList>();
|
|||
|
SqlConnection _SQLServerSourceConnection = null;
|
|||
|
SqlConnection _SQLServerDestinationConnection = null;
|
|||
|
DataTable _dtIdentityColumns = null;
|
|||
|
string _sourceConnetionString;
|
|||
|
string _destinationConnetionString;
|
|||
|
static Dictionary<string, bool> _dataTypes = new Dictionary<string, bool>();
|
|||
|
public Form1()
|
|||
|
{
|
|||
|
InitializeComponent();
|
|||
|
}
|
|||
|
[Serializable]
|
|||
|
public enum EnumTargetType
|
|||
|
{
|
|||
|
Source = 1,
|
|||
|
Destination = 2
|
|||
|
}
|
|||
|
[Serializable]
|
|||
|
public enum EnumParamType
|
|||
|
{
|
|||
|
InParamType = 1,
|
|||
|
EqualParamType = 2
|
|||
|
}
|
|||
|
[Serializable]
|
|||
|
public enum EnumDBType
|
|||
|
{
|
|||
|
SqlServer = 1,
|
|||
|
Oracle = 2,
|
|||
|
MySql = 3
|
|||
|
}
|
|||
|
[Serializable]
|
|||
|
public enum EnumScriptType
|
|||
|
{
|
|||
|
CreateTable = 1,
|
|||
|
AlterTable = 2,
|
|||
|
AlterColumn = 3
|
|||
|
}
|
|||
|
private void btnGetSource_Click(object sender, EventArgs e)
|
|||
|
{
|
|||
|
Cursor.Current = Cursors.WaitCursor;
|
|||
|
try
|
|||
|
{
|
|||
|
GetConnection(EnumTargetType.Source, txtSourceServer.Text, txtSourceUserNane.Text, txtSourcePassword.Text);
|
|||
|
cmbSourceDatabase.DataSource = null;
|
|||
|
cmbSourceDatabase.Items.Clear();
|
|||
|
cmbSourceDatabase.DataSource = (GetDatabaseList(EnumTargetType.Source));
|
|||
|
cmbSourceDatabase.DisplayMember = "Name";
|
|||
|
cmbSourceDatabase.SelectedIndex = 0;
|
|||
|
}
|
|||
|
catch (Exception exp)
|
|||
|
{
|
|||
|
MessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
|||
|
}
|
|||
|
finally
|
|||
|
{
|
|||
|
Cursor.Current = Cursors.Default;
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
private void GetConnection(EnumTargetType eTargetType, string sServer, string sName, string sPassword)
|
|||
|
{
|
|||
|
if (eTargetType == EnumTargetType.Source)
|
|||
|
_sourceConnetionString = @"Data Source=" + sServer + ";User ID=" + sName + ";Password=" + sPassword + ";";
|
|||
|
else
|
|||
|
_destinationConnetionString = @"Data Source=" + sServer + ";User ID=" + sName + ";Password=" + sPassword + ";";
|
|||
|
}
|
|||
|
private void GetConnection(EnumTargetType eTargetType, string sServer, string sDatabase, string sName, string sPassword)
|
|||
|
{
|
|||
|
if (eTargetType == EnumTargetType.Source)
|
|||
|
_sourceConnetionString = @"Data Source=" + sServer + ";Initial Catalog=" + sDatabase + ";User ID =" + sName + ";Password=" + sPassword + ";";
|
|||
|
else
|
|||
|
_destinationConnetionString = @"Data Source=" + sServer + ";Initial Catalog=" + sDatabase + ";User ID =" + sName + ";Password=" + sPassword + ";";
|
|||
|
}
|
|||
|
public List<string> GetDatabaseList(EnumTargetType eTargetType)
|
|||
|
{
|
|||
|
List<string> list = new List<string>();
|
|||
|
string Connection = "";
|
|||
|
if (eTargetType == EnumTargetType.Source)
|
|||
|
Connection = _sourceConnetionString;
|
|||
|
else
|
|||
|
Connection = _destinationConnetionString;
|
|||
|
using (SqlConnection con = new SqlConnection(Connection))
|
|||
|
{
|
|||
|
con.Open();
|
|||
|
using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases order by name", con))
|
|||
|
{
|
|||
|
using (IDataReader dr = cmd.ExecuteReader())
|
|||
|
{
|
|||
|
while (dr.Read())
|
|||
|
{
|
|||
|
list.Add(dr[0].ToString());
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
con.Close();
|
|||
|
}
|
|||
|
return list;
|
|||
|
}
|
|||
|
public List<string> GetTableList(EnumTargetType eTargetType)
|
|||
|
{
|
|||
|
try
|
|||
|
{
|
|||
|
List<string> list = new List<string>();
|
|||
|
string Connection = "";
|
|||
|
if (eTargetType == EnumTargetType.Source)
|
|||
|
Connection = _sourceConnetionString;
|
|||
|
else
|
|||
|
Connection = _destinationConnetionString;
|
|||
|
using (SqlConnection con = new SqlConnection(Connection))
|
|||
|
{
|
|||
|
con.Open();
|
|||
|
using (SqlCommand cmd = new SqlCommand("SELECT name FROM sys.Tables order by name", con))
|
|||
|
{
|
|||
|
using (IDataReader dr = cmd.ExecuteReader())
|
|||
|
{
|
|||
|
while (dr.Read())
|
|||
|
{
|
|||
|
list.Add(dr[0].ToString());
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
con.Close();
|
|||
|
}
|
|||
|
return list;
|
|||
|
}
|
|||
|
catch (Exception exp)
|
|||
|
{
|
|||
|
throw new Exception(exp.Message);
|
|||
|
}
|
|||
|
}
|
|||
|
public DataTable GetColumnList(EnumTargetType eTargetType, string sTableName)
|
|||
|
{
|
|||
|
//List<string, string> list = new List<string>();
|
|||
|
try
|
|||
|
{
|
|||
|
DataTable dt = new DataTable();
|
|||
|
string Connection = "";
|
|||
|
if (eTargetType == EnumTargetType.Source)
|
|||
|
Connection = _sourceConnetionString;
|
|||
|
else
|
|||
|
Connection = _destinationConnetionString;
|
|||
|
using (SqlConnection con = new SqlConnection(Connection))
|
|||
|
{
|
|||
|
con.Open();
|
|||
|
using (SqlCommand cmd = new SqlCommand("SELECT column_name, data_type,character_maximum_length,IS_NULLABLE,COLUMN_DEFAULT, NUMERIC_PRECISION,NUMERIC_SCALE FROM information_schema.columns WHERE table_name = '" + sTableName + "' ORDER BY ORDINAL_POSITION", con))
|
|||
|
{
|
|||
|
using (IDataReader dr = cmd.ExecuteReader())
|
|||
|
{
|
|||
|
dt.Load(dr);
|
|||
|
}
|
|||
|
}
|
|||
|
con.Close();
|
|||
|
}
|
|||
|
return dt;
|
|||
|
}
|
|||
|
catch (Exception exp)
|
|||
|
{
|
|||
|
throw new Exception(exp.Message);
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
public DataTable GetIdentityColumnList(EnumTargetType eTargetType)
|
|||
|
{
|
|||
|
//List<string, string> list = new List<string>();
|
|||
|
try
|
|||
|
{
|
|||
|
DataTable dt = new DataTable();
|
|||
|
string Connection = "";
|
|||
|
if (eTargetType == EnumTargetType.Source)
|
|||
|
Connection = _sourceConnetionString;
|
|||
|
else
|
|||
|
Connection = _destinationConnetionString;
|
|||
|
using (SqlConnection con = new SqlConnection(Connection))
|
|||
|
{
|
|||
|
con.Open();
|
|||
|
using (SqlCommand cmd = new SqlCommand(@"select o.name, c.name
|
|||
|
from sys.objects o inner
|
|||
|
join sys.columns c on o.object_id = c.object_id
|
|||
|
where c.is_identity = 1", con))
|
|||
|
{
|
|||
|
using (IDataReader dr = cmd.ExecuteReader())
|
|||
|
{
|
|||
|
dt.Load(dr);
|
|||
|
}
|
|||
|
}
|
|||
|
con.Close();
|
|||
|
}
|
|||
|
return dt;
|
|||
|
}
|
|||
|
catch (Exception exp)
|
|||
|
{
|
|||
|
throw new Exception(exp.Message);
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
public string UpdateColumn(string sTableName, string sColumnName, string sValue, string sCondition)
|
|||
|
{
|
|||
|
string sSqlCommand = "";
|
|||
|
|
|||
|
if (sCondition == "")
|
|||
|
{
|
|||
|
sSqlCommand = "IF COL_LENGTH('dbo." + sTableName + "', '" + sColumnName + "') IS NOT NULL " +
|
|||
|
" BEGIN " +
|
|||
|
" update " + sTableName + " set " + sColumnName + " ='" + sValue + "' " +
|
|||
|
" END ";
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
sSqlCommand = "IF COL_LENGTH('dbo." + sTableName + "', '" + sColumnName + "') IS NOT NULL " +
|
|||
|
" BEGIN " +
|
|||
|
" update " + sTableName + " set " + sColumnName + " ='" + sValue + "' WHERE " + sCondition +
|
|||
|
" END ";
|
|||
|
}
|
|||
|
|
|||
|
return sSqlCommand;
|
|||
|
}
|
|||
|
public DataTable GePrimaryKeyList(EnumTargetType eTargetType)
|
|||
|
{
|
|||
|
//List<string, string> list = new List<string>();
|
|||
|
try
|
|||
|
{
|
|||
|
DataTable dt = new DataTable();
|
|||
|
string Connection = "";
|
|||
|
if (eTargetType == EnumTargetType.Source)
|
|||
|
Connection = _sourceConnetionString;
|
|||
|
else
|
|||
|
Connection = _destinationConnetionString;
|
|||
|
using (SqlConnection con = new SqlConnection(Connection))
|
|||
|
{
|
|||
|
con.Open();
|
|||
|
using (SqlCommand cmd = new SqlCommand(@"SELECT OBJECT_NAME(ic.OBJECT_ID) AS TableName, c.name AS ColumnName, i.name AS ConstraintName FROM
|
|||
|
sys.indexes AS i
|
|||
|
INNER JOIN
|
|||
|
sys.index_columns AS ic ON i.OBJECT_ID = ic.OBJECT_ID AND i.index_id = ic.index_id
|
|||
|
INNER JOIN
|
|||
|
sys.columns AS c ON ic.OBJECT_ID = c.OBJECT_ID AND ic.column_id = c.column_id
|
|||
|
WHERE
|
|||
|
i.is_primary_key = 1;", con))
|
|||
|
{
|
|||
|
using (IDataReader dr = cmd.ExecuteReader())
|
|||
|
{
|
|||
|
dt.Load(dr);
|
|||
|
}
|
|||
|
}
|
|||
|
con.Close();
|
|||
|
}
|
|||
|
return dt;
|
|||
|
}
|
|||
|
catch (Exception exp)
|
|||
|
{
|
|||
|
throw new Exception(exp.Message);
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
public DataTable GeForeignKeyList(EnumTargetType eTargetType)
|
|||
|
{
|
|||
|
//List<string, string> list = new List<string>();
|
|||
|
try
|
|||
|
{
|
|||
|
DataTable dt = new DataTable();
|
|||
|
string Connection = "";
|
|||
|
if (eTargetType == EnumTargetType.Source)
|
|||
|
Connection = _sourceConnetionString;
|
|||
|
else
|
|||
|
Connection = _destinationConnetionString;
|
|||
|
using (SqlConnection con = new SqlConnection(Connection))
|
|||
|
{
|
|||
|
con.Open();
|
|||
|
using (SqlCommand cmd = new SqlCommand(@"SELECT
|
|||
|
f.name AS Constraint_Name,
|
|||
|
OBJECT_NAME(f.parent_object_id) AS FK_Table,
|
|||
|
c1.name AS FK_Column,
|
|||
|
OBJECT_NAME(f.referenced_object_id) AS Reference_Table,
|
|||
|
c2.name AS Referenced_Column
|
|||
|
FROM sys.foreign_keys AS f
|
|||
|
INNER JOIN sys.foreign_key_columns AS fk_cols ON f.object_id = fk_cols.constraint_object_id
|
|||
|
INNER JOIN sys.columns AS c1 ON f.parent_object_id = c1.object_id AND fk_cols.parent_column_id = c1.column_id
|
|||
|
INNER JOIN sys.columns AS c2 ON f.referenced_object_id = c2.object_id AND fk_cols.referenced_column_id = c2.column_id;", con))
|
|||
|
{
|
|||
|
using (IDataReader dr = cmd.ExecuteReader())
|
|||
|
{
|
|||
|
dt.Load(dr);
|
|||
|
}
|
|||
|
}
|
|||
|
con.Close();
|
|||
|
}
|
|||
|
return dt;
|
|||
|
}
|
|||
|
catch (Exception exp)
|
|||
|
{
|
|||
|
throw new Exception(exp.Message);
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
public DataTable GetDefaultConstraint(EnumTargetType eTargetType)
|
|||
|
{
|
|||
|
//List<string, string> list = new List<string>();
|
|||
|
try
|
|||
|
{
|
|||
|
DataTable dt = new DataTable();
|
|||
|
string Connection = "";
|
|||
|
if (eTargetType == EnumTargetType.Source)
|
|||
|
Connection = _sourceConnetionString;
|
|||
|
else
|
|||
|
Connection = _destinationConnetionString;
|
|||
|
using (SqlConnection con = new SqlConnection(Connection))
|
|||
|
{
|
|||
|
con.Open();
|
|||
|
using (SqlCommand cmd = new SqlCommand(@"SELECT
|
|||
|
t.name AS TableName,
|
|||
|
c.name AS ColumnName,
|
|||
|
d.name AS DefaultConstraintName,
|
|||
|
d.definition AS DefaultDefinition
|
|||
|
FROM sys.default_constraints d
|
|||
|
INNER JOIN sys.columns c ON
|
|||
|
d.parent_object_id = c.object_id
|
|||
|
AND d.parent_column_id = c.column_id
|
|||
|
INNER JOIN sys.tables t ON
|
|||
|
t.object_id = c.object_id", con))
|
|||
|
{
|
|||
|
using (IDataReader dr = cmd.ExecuteReader())
|
|||
|
{
|
|||
|
dt.Load(dr);
|
|||
|
}
|
|||
|
}
|
|||
|
con.Close();
|
|||
|
}
|
|||
|
return dt;
|
|||
|
}
|
|||
|
catch (Exception exp)
|
|||
|
{
|
|||
|
throw new Exception(exp.Message);
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
public DataTable GetColumnList(EnumTargetType eTargetType)
|
|||
|
{
|
|||
|
//List<string, string> list = new List<string>();
|
|||
|
try
|
|||
|
{
|
|||
|
DataTable dt = new DataTable();
|
|||
|
string Connection = "";
|
|||
|
if (eTargetType == EnumTargetType.Source)
|
|||
|
Connection = _sourceConnetionString;
|
|||
|
else
|
|||
|
Connection = _destinationConnetionString;
|
|||
|
using (SqlConnection con = new SqlConnection(Connection))
|
|||
|
{
|
|||
|
con.Open();
|
|||
|
using (SqlCommand cmd = new SqlCommand(@"select 'sp_RENAME ''' + t.name + '.' + QUOTENAME(c.Column_Name) + ''', ''' + UPPER(c.Column_Name) + ''', ''COLUMN'';' As Command
|
|||
|
from sys.tables t
|
|||
|
INNER JOIN information_schema.columns c ON c.Table_Name = t.Name
|
|||
|
WHERE lower(t.name)IN('monthlyworkplan', 'dailyattnprocess', 'attnrawdata',
|
|||
|
'salarymonthly', 'salarymonthlydetail',
|
|||
|
'salaryempcostcenter', 'salarytempit', 'incometaxtemp', 'bonustempit','incometaxyearly')
|
|||
|
ORDER BY t.name", con))
|
|||
|
{
|
|||
|
using (IDataReader dr = cmd.ExecuteReader())
|
|||
|
{
|
|||
|
dt.Load(dr);
|
|||
|
}
|
|||
|
}
|
|||
|
con.Close();
|
|||
|
}
|
|||
|
return dt;
|
|||
|
}
|
|||
|
catch (Exception exp)
|
|||
|
{
|
|||
|
throw new Exception(exp.Message);
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
private void cmbSourceDatabase_SelectedIndexChanged(object sender, EventArgs e)
|
|||
|
{
|
|||
|
Cursor.Current = Cursors.WaitCursor;
|
|||
|
try
|
|||
|
{
|
|||
|
GetConnection(EnumTargetType.Source, txtSourceServer.Text, cmbSourceDatabase.Text, txtSourceUserNane.Text, txtSourcePassword.Text);
|
|||
|
List<string> sTables = GetTableList(EnumTargetType.Source);
|
|||
|
FillSourceList(sTables);
|
|||
|
lblSourceCount.Text = "Total Table :" + sTables.Count;
|
|||
|
}
|
|||
|
catch (Exception exp)
|
|||
|
{
|
|||
|
MessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
|||
|
}
|
|||
|
finally
|
|||
|
{
|
|||
|
Cursor.Current = Cursors.Default;
|
|||
|
}
|
|||
|
}
|
|||
|
private void FillSourceList(List<string> sTables)
|
|||
|
{
|
|||
|
lsvSourceList.Items.Clear();
|
|||
|
ListViewItem li = null;
|
|||
|
foreach (string sName in sTables)
|
|||
|
{
|
|||
|
li = new ListViewItem();
|
|||
|
li.Text = sName;
|
|||
|
lsvSourceList.Items.Add(li);
|
|||
|
}
|
|||
|
}
|
|||
|
private void FillDestinationList(List<string> sTables)
|
|||
|
{
|
|||
|
lsvDestinationList.Items.Clear();
|
|||
|
ListViewItem li = null;
|
|||
|
foreach (string sName in sTables)
|
|||
|
{
|
|||
|
li = new ListViewItem();
|
|||
|
li.Text = sName;
|
|||
|
lsvDestinationList.Items.Add(li);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
private void cmbDestinationDatabase_SelectedIndexChanged(object sender, EventArgs e)
|
|||
|
{
|
|||
|
Cursor.Current = Cursors.WaitCursor;
|
|||
|
try
|
|||
|
{
|
|||
|
GetConnection(EnumTargetType.Destination, txtDestinationServer.Text, cmbDestinationDatabase.Text, txtDestinationUserNane.Text, txtDestinationPassword.Text);
|
|||
|
List<string> sTables = GetTableList(EnumTargetType.Destination);
|
|||
|
FillDestinationList(sTables);
|
|||
|
lblDestinationCount.Text = "Total Table :" + sTables.Count;
|
|||
|
}
|
|||
|
catch (Exception exp)
|
|||
|
{
|
|||
|
MessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
|||
|
}
|
|||
|
finally
|
|||
|
{
|
|||
|
Cursor.Current = Cursors.Default;
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
private void btnGetDestination_Click(object sender, EventArgs e)
|
|||
|
{
|
|||
|
Cursor.Current = Cursors.WaitCursor;
|
|||
|
try
|
|||
|
{
|
|||
|
GetConnection(EnumTargetType.Destination, txtDestinationServer.Text, txtDestinationUserNane.Text, txtDestinationPassword.Text);
|
|||
|
|
|||
|
cmbDestinationDatabase.Items.Clear();
|
|||
|
cmbDestinationDatabase.DataSource = (GetDatabaseList(EnumTargetType.Destination));
|
|||
|
cmbDestinationDatabase.DisplayMember = "Name";
|
|||
|
cmbDestinationDatabase.SelectedIndex = 0;
|
|||
|
}
|
|||
|
catch (Exception exp)
|
|||
|
{
|
|||
|
MessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
|||
|
}
|
|||
|
finally
|
|||
|
{
|
|||
|
Cursor.Current = Cursors.Default;
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
public bool IsTableExists(string sTableName)
|
|||
|
{
|
|||
|
bool found = false;
|
|||
|
foreach (ListViewItem li in lsvDestinationList.Items)
|
|||
|
{
|
|||
|
if (sTableName.ToLower().Trim() == li.Text.ToLower().Trim())
|
|||
|
{
|
|||
|
found = true;
|
|||
|
break;
|
|||
|
}
|
|||
|
}
|
|||
|
return found;
|
|||
|
}
|
|||
|
public bool IsColumnExists(DataRow dr, DataTable lsv)
|
|||
|
{
|
|||
|
bool found = false;
|
|||
|
foreach (DataRow li in lsv.Rows)
|
|||
|
{
|
|||
|
if (dr[0].ToString().ToLower().Trim() == li[0].ToString().ToLower().Trim())
|
|||
|
{
|
|||
|
found = true;
|
|||
|
break;
|
|||
|
}
|
|||
|
}
|
|||
|
return found;
|
|||
|
}
|
|||
|
public bool IsColumnExistsWithType(DataRow dr, DataTable lsv)
|
|||
|
{
|
|||
|
bool found = false;
|
|||
|
foreach (DataRow li in lsv.Rows)
|
|||
|
{
|
|||
|
if (dr[0].ToString().ToLower().Trim() == li[0].ToString().ToLower().Trim()
|
|||
|
&& dr[1].ToString().ToLower().Trim() == li[1].ToString().ToLower().Trim()
|
|||
|
&& dr[3].ToString().ToLower().Trim() == li[3].ToString().ToLower().Trim()
|
|||
|
&& dr[4].ToString().ToLower().Trim() == li[4].ToString().ToLower().Trim()
|
|||
|
&& dr[5].ToString().ToLower().Trim() == li[5].ToString().ToLower().Trim()
|
|||
|
&& dr[6].ToString().ToLower().Trim() == li[6].ToString().ToLower().Trim())
|
|||
|
{
|
|||
|
found = true;
|
|||
|
break;
|
|||
|
}
|
|||
|
|
|||
|
if (dr[0].ToString().ToLower().Trim() == li[0].ToString().ToLower().Trim()
|
|||
|
&& dr[1].ToString().ToLower().Trim() == li[1].ToString().ToLower().Trim()
|
|||
|
&& dr[3].ToString().ToLower().Trim() == li[3].ToString().ToLower().Trim()
|
|||
|
&& dr[5].ToString().ToLower().Trim() == li[5].ToString().ToLower().Trim()
|
|||
|
&& dr[6].ToString().ToLower().Trim() == li[6].ToString().ToLower().Trim()
|
|||
|
&& dr[4].ToString().ToLower().Trim() == "" && li[4].ToString().ToLower().Trim() != "")
|
|||
|
{
|
|||
|
found = true;
|
|||
|
break;
|
|||
|
}
|
|||
|
|
|||
|
//int nSourceSize = 0;
|
|||
|
//int nDestinationSize = 0;
|
|||
|
//try
|
|||
|
//{
|
|||
|
// nSourceSize = Convert.ToInt16(dr[2].ToString().ToLower().Trim());
|
|||
|
//}
|
|||
|
//catch { }
|
|||
|
//try
|
|||
|
//{
|
|||
|
// nDestinationSize = Convert.ToInt16(li[2].ToString().ToLower().Trim());
|
|||
|
//}
|
|||
|
//catch { }
|
|||
|
//if (dr[0].ToString().ToLower().Trim() == li[0].ToString().ToLower().Trim()
|
|||
|
// && dr[1].ToString().ToLower().Trim() == li[1].ToString().ToLower().Trim()
|
|||
|
// && nSourceSize < nDestinationSize
|
|||
|
// && dr[3].ToString().ToLower().Trim() == li[3].ToString().ToLower().Trim()
|
|||
|
// && dr[4].ToString().ToLower().Trim() == li[4].ToString().ToLower().Trim()
|
|||
|
// && dr[5].ToString().ToLower().Trim() == li[5].ToString().ToLower().Trim()
|
|||
|
// && dr[6].ToString().ToLower().Trim() == li[6].ToString().ToLower().Trim())
|
|||
|
//{
|
|||
|
// found = true;
|
|||
|
// break;
|
|||
|
//}
|
|||
|
|
|||
|
}
|
|||
|
return found;
|
|||
|
}
|
|||
|
private TableList GetObject(string sTableName, DataRow dr)
|
|||
|
{
|
|||
|
TableList oItem = new TableList();
|
|||
|
oItem.TableName = sTableName.ToUpper();
|
|||
|
oItem.ColumnName = dr[0].ToString().ToUpper();
|
|||
|
oItem.DataType = dr[1].ToString().ToUpper();
|
|||
|
oItem.Length = dr[2].ToString().ToUpper();
|
|||
|
oItem.AllowNull = dr[3].ToString().ToUpper();
|
|||
|
oItem.DefaultValue = dr[4].ToString().ToUpper();
|
|||
|
oItem.Precision = dr[5].ToString().ToUpper();
|
|||
|
oItem.Scale = dr[6].ToString().ToUpper();
|
|||
|
oItem.IsDefaultValueRequired = false;
|
|||
|
return oItem;
|
|||
|
}
|
|||
|
private void btnCompate_Click(object sender, EventArgs e)
|
|||
|
{
|
|||
|
var watch = System.Diagnostics.Stopwatch.StartNew();
|
|||
|
Cursor.Current = Cursors.WaitCursor;
|
|||
|
StringBuilder sbCreate = new StringBuilder();
|
|||
|
StringBuilder sbAlterMain = new StringBuilder();
|
|||
|
StringBuilder sbAlter = new StringBuilder();
|
|||
|
IEnumerable<ListViewItem> lv = lsvDestinationList.Items.Cast<ListViewItem>();
|
|||
|
_oTableLists = new List<TableList>();
|
|||
|
foreach (ListViewItem li in lsvSourceList.CheckedItems)
|
|||
|
{
|
|||
|
TableList oItem = null;
|
|||
|
lblMsg.Text = "Compare Table : " + li.Text;
|
|||
|
lblMsg.Refresh();
|
|||
|
if (IsTableExists(li.Text))
|
|||
|
{
|
|||
|
bool diff = false;
|
|||
|
GetConnection(EnumTargetType.Source, txtSourceServer.Text, cmbSourceDatabase.Text, txtSourceUserNane.Text, txtSourcePassword.Text);
|
|||
|
DataTable dtSource = GetColumnList(EnumTargetType.Source, li.Text);
|
|||
|
GetConnection(EnumTargetType.Destination, txtDestinationServer.Text, cmbDestinationDatabase.Text, txtDestinationUserNane.Text, txtDestinationPassword.Text);
|
|||
|
DataTable dtDestination = GetColumnList(EnumTargetType.Destination, li.Text);
|
|||
|
|
|||
|
int nCount = 1;
|
|||
|
int nDiffCount = 1;
|
|||
|
|
|||
|
foreach (DataRow dr in dtSource.Rows)
|
|||
|
{
|
|||
|
if (!IsColumnExists(dr, dtDestination))
|
|||
|
{
|
|||
|
oItem = GetObject(li.Text, dr);
|
|||
|
oItem.ScriptType = EnumScriptType.AlterTable;
|
|||
|
if (dr[1].ToString().ToLower() == "int")
|
|||
|
{
|
|||
|
oItem.Precision = "";
|
|||
|
oItem.Scale = "";
|
|||
|
}
|
|||
|
else if (dr[1].ToString().ToLower() == "float")
|
|||
|
{
|
|||
|
oItem.Length = oItem.Precision;
|
|||
|
oItem.Precision = "";
|
|||
|
}
|
|||
|
if ((dr[1].ToString().ToLower() == "varchar"
|
|||
|
|| dr[1].ToString().ToLower() == "nvarchar"
|
|||
|
|| dr[1].ToString().ToLower() == "varbinary") && dr[2].ToString() == "-1")
|
|||
|
{
|
|||
|
oItem.Length = "MAX";
|
|||
|
}
|
|||
|
else if (dr[1].ToString().ToLower() == "text")
|
|||
|
{
|
|||
|
oItem.Length = "";
|
|||
|
}
|
|||
|
|
|||
|
if (dr[3].ToString().ToLower() == "no")
|
|||
|
{
|
|||
|
if (dr[4].ToString().ToLower() == "")
|
|||
|
{
|
|||
|
if (dr[1].ToString().ToLower() == "date" ||
|
|||
|
dr[1].ToString().ToLower() == "datetime" ||
|
|||
|
dr[1].ToString().ToLower() == "datetime2")
|
|||
|
oItem.DefaultValue = "GETDATE()";
|
|||
|
else if (dr[1].ToString().ToLower() == "char" ||
|
|||
|
dr[1].ToString().ToLower() == "nchar" ||
|
|||
|
dr[1].ToString().ToLower() == "varchar" ||
|
|||
|
dr[1].ToString().ToLower() == "nvarchar" ||
|
|||
|
dr[1].ToString().ToLower() == "text")
|
|||
|
oItem.DefaultValue = "''";
|
|||
|
else if (dr[1].ToString().ToLower() == "int" ||
|
|||
|
dr[1].ToString().ToLower() == "bit" ||
|
|||
|
dr[1].ToString().ToLower() == "smallint" ||
|
|||
|
dr[1].ToString().ToLower() == "money" ||
|
|||
|
dr[1].ToString().ToLower() == "numeric" ||
|
|||
|
dr[1].ToString().ToLower() == "decimal" ||
|
|||
|
dr[1].ToString().ToLower() == "float" ||
|
|||
|
dr[1].ToString().ToLower() == "tinyint")
|
|||
|
oItem.DefaultValue = "0";
|
|||
|
oItem.IsDefaultValueRequired = true;
|
|||
|
}
|
|||
|
}
|
|||
|
if (oItem.ColumnName.ToLower() == "payrolltypeid" || oItem.ColumnName.ToLower() == "createdby")
|
|||
|
{
|
|||
|
oItem.AllowNull = "NO";
|
|||
|
oItem.DefaultValue = textBox2.Text == "" ? "1" : textBox2.Text;
|
|||
|
if (oItem.ColumnName.ToLower() == "createdby")
|
|||
|
oItem.DefaultValue = textBox1.Text == "" ? "1" : textBox2.Text;
|
|||
|
}
|
|||
|
_oTableLists.Add(oItem);
|
|||
|
}
|
|||
|
nCount++;
|
|||
|
}
|
|||
|
foreach (DataRow dr in dtSource.Rows)
|
|||
|
{
|
|||
|
if (!IsColumnExistsWithType(dr, dtDestination))
|
|||
|
{
|
|||
|
oItem = GetObject(li.Text, dr);
|
|||
|
TableList ob = _oTableLists.Find(x => x.TableName == oItem.TableName && x.ColumnName == oItem.ColumnName && x.ScriptType == EnumScriptType.AlterTable);
|
|||
|
if (ob != null)
|
|||
|
{
|
|||
|
nCount++;
|
|||
|
continue;
|
|||
|
}
|
|||
|
oItem.ScriptType = EnumScriptType.AlterColumn;
|
|||
|
if (dr[1].ToString().ToLower() == "int")
|
|||
|
{
|
|||
|
oItem.Precision = "";
|
|||
|
oItem.Scale = "";
|
|||
|
}
|
|||
|
else if (dr[1].ToString().ToLower() == "float")
|
|||
|
{
|
|||
|
oItem.Length = oItem.Precision;
|
|||
|
oItem.Precision = "";
|
|||
|
}
|
|||
|
if ((dr[1].ToString().ToLower() == "varchar"
|
|||
|
|| dr[1].ToString().ToLower() == "nvarchar"
|
|||
|
|| dr[1].ToString().ToLower() == "varbinary") && dr[2].ToString() == "-1")
|
|||
|
{
|
|||
|
oItem.Length = "MAX";
|
|||
|
}
|
|||
|
else if (dr[1].ToString().ToLower() == "text")
|
|||
|
{
|
|||
|
oItem.Length = "";
|
|||
|
}
|
|||
|
if (dr[3].ToString().ToLower() == "no")
|
|||
|
{
|
|||
|
if (dr[4].ToString().ToLower() == "")
|
|||
|
{
|
|||
|
if (dr[1].ToString().ToLower() == "date" ||
|
|||
|
dr[1].ToString().ToLower() == "datetime" ||
|
|||
|
dr[1].ToString().ToLower() == "datetime2")
|
|||
|
oItem.DefaultValue = "GETDATE()";
|
|||
|
else if (dr[1].ToString().ToLower() == "char" ||
|
|||
|
dr[1].ToString().ToLower() == "nchar" ||
|
|||
|
dr[1].ToString().ToLower() == "varchar" ||
|
|||
|
dr[1].ToString().ToLower() == "nvarchar" ||
|
|||
|
dr[1].ToString().ToLower() == "text")
|
|||
|
oItem.DefaultValue = "''";
|
|||
|
else if (dr[1].ToString().ToLower() == "int" ||
|
|||
|
dr[1].ToString().ToLower() == "bit" ||
|
|||
|
dr[1].ToString().ToLower() == "smallint" ||
|
|||
|
dr[1].ToString().ToLower() == "money" ||
|
|||
|
dr[1].ToString().ToLower() == "numeric" ||
|
|||
|
dr[1].ToString().ToLower() == "decimal" ||
|
|||
|
dr[1].ToString().ToLower() == "float" ||
|
|||
|
dr[1].ToString().ToLower() == "tinyint")
|
|||
|
oItem.DefaultValue = "0";
|
|||
|
|
|||
|
oItem.IsDefaultValueRequired = true;
|
|||
|
}
|
|||
|
}
|
|||
|
if (oItem.ColumnName.ToLower() == "payrolltypeid" || oItem.ColumnName.ToLower() == "createdby")
|
|||
|
{
|
|||
|
oItem.AllowNull = "NO";
|
|||
|
oItem.DefaultValue = textBox2.Text == "" ? "1" : textBox2.Text;
|
|||
|
if (oItem.ColumnName.ToLower() == "createdby")
|
|||
|
oItem.DefaultValue = textBox1.Text == "" ? "1" : textBox2.Text;
|
|||
|
}
|
|||
|
_oTableLists.Add(oItem);
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
|
|||
|
}
|
|||
|
nCount++;
|
|||
|
}
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
GetConnection(EnumTargetType.Source, txtSourceServer.Text, cmbSourceDatabase.Text, txtSourceUserNane.Text, txtSourcePassword.Text);
|
|||
|
DataTable dt = GetColumnList(EnumTargetType.Source, li.Text);
|
|||
|
int nCount = 1;
|
|||
|
if (dt != null && dt.Rows.Count > 0)
|
|||
|
{
|
|||
|
foreach (DataRow dr in dt.Rows)
|
|||
|
{
|
|||
|
oItem = GetObject(li.Text, dr);
|
|||
|
oItem.ScriptType = EnumScriptType.CreateTable;
|
|||
|
//if (nCount != 1)
|
|||
|
//{
|
|||
|
// oItem.TableName = "";
|
|||
|
//}
|
|||
|
if (dr[1].ToString().ToLower() == "int")
|
|||
|
{
|
|||
|
oItem.Precision = "";
|
|||
|
oItem.Scale = "";
|
|||
|
}
|
|||
|
else if (dr[1].ToString().ToLower() == "float")
|
|||
|
{
|
|||
|
oItem.Length = oItem.Precision;
|
|||
|
oItem.Precision = "";
|
|||
|
}
|
|||
|
if ((dr[1].ToString().ToLower() == "varchar"
|
|||
|
|| dr[1].ToString().ToLower() == "nvarchar"
|
|||
|
|| dr[1].ToString().ToLower() == "varbinary") && dr[2].ToString() == "-1")
|
|||
|
{
|
|||
|
oItem.Length = "MAX";
|
|||
|
}
|
|||
|
else if (dr[1].ToString().ToLower() == "text")
|
|||
|
{
|
|||
|
oItem.Length = "";
|
|||
|
}
|
|||
|
nCount++;
|
|||
|
_oTableLists.Add(oItem);
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
FillGridView();
|
|||
|
Cursor.Current = Cursors.Default;
|
|||
|
watch.Stop();
|
|||
|
var elapsedMs = watch.ElapsedMilliseconds / 1000;
|
|||
|
lblMsg.Text = "Total Time Elapsed :" + CalculateTimeElapsed(elapsedMs);
|
|||
|
lblMsg.Refresh();
|
|||
|
}
|
|||
|
private string CalculateTimeElapsed(long nTime)
|
|||
|
{
|
|||
|
TimeSpan t = TimeSpan.FromSeconds(nTime);
|
|||
|
|
|||
|
string answer = string.Format("{0:D2} h:{1:D2} m:{2:D2} s",
|
|||
|
t.Hours,
|
|||
|
t.Minutes,
|
|||
|
t.Seconds);
|
|||
|
return answer;
|
|||
|
}
|
|||
|
private void FillGridView()
|
|||
|
{
|
|||
|
grdList.Rows.Clear();
|
|||
|
foreach (TableList li in _oTableLists)
|
|||
|
{
|
|||
|
int RowIndex = grdList.Rows.Add();
|
|||
|
DataGridViewRow oRow = grdList.Rows[RowIndex];
|
|||
|
oRow.Cells[0].Style.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F, System.Drawing.FontStyle.Bold);
|
|||
|
if (li.ScriptType == EnumScriptType.CreateTable)
|
|||
|
{
|
|||
|
oRow.Cells[0].Style.ForeColor = Color.Red;
|
|||
|
oRow.Cells[1].Style.ForeColor = Color.Red;
|
|||
|
oRow.Cells[2].Style.ForeColor = Color.Red;
|
|||
|
oRow.Cells[3].Style.ForeColor = Color.Red;
|
|||
|
oRow.Cells[4].Style.ForeColor = Color.Red;
|
|||
|
oRow.Cells[5].Style.ForeColor = Color.Red;
|
|||
|
oRow.Cells[7].Style.ForeColor = Color.Red;
|
|||
|
oRow.Cells[8].Style.ForeColor = Color.Red;
|
|||
|
}
|
|||
|
else if (li.ScriptType == EnumScriptType.AlterTable)
|
|||
|
{
|
|||
|
oRow.Cells[0].Style.ForeColor = Color.Green;
|
|||
|
oRow.Cells[1].Style.ForeColor = Color.Green;
|
|||
|
oRow.Cells[2].Style.ForeColor = Color.Green;
|
|||
|
oRow.Cells[3].Style.ForeColor = Color.Green;
|
|||
|
oRow.Cells[4].Style.ForeColor = Color.Green;
|
|||
|
oRow.Cells[5].Style.ForeColor = Color.Green;
|
|||
|
oRow.Cells[7].Style.ForeColor = Color.Green;
|
|||
|
oRow.Cells[8].Style.ForeColor = Color.Green;
|
|||
|
}
|
|||
|
else if (li.ScriptType == EnumScriptType.AlterColumn)
|
|||
|
{
|
|||
|
oRow.Cells[0].Style.ForeColor = Color.Purple;
|
|||
|
oRow.Cells[1].Style.ForeColor = Color.Purple;
|
|||
|
oRow.Cells[2].Style.ForeColor = Color.Purple;
|
|||
|
oRow.Cells[3].Style.ForeColor = Color.Purple;
|
|||
|
oRow.Cells[4].Style.ForeColor = Color.Purple;
|
|||
|
oRow.Cells[5].Style.ForeColor = Color.Purple;
|
|||
|
oRow.Cells[7].Style.ForeColor = Color.Purple;
|
|||
|
oRow.Cells[8].Style.ForeColor = Color.Purple;
|
|||
|
}
|
|||
|
oRow.Cells[0].Value = li.TableName;
|
|||
|
oRow.Cells[1].Value = li.ColumnName;
|
|||
|
oRow.Cells[2].Value = li.DataType;
|
|||
|
oRow.Cells[3].Value = li.Length;
|
|||
|
oRow.Cells[4].Value = li.AllowNull;
|
|||
|
oRow.Cells[5].Value = li.DefaultValue;
|
|||
|
oRow.Cells[6].Value = li.IsDefaultValueRequired ? "Yes" : "No";
|
|||
|
oRow.Cells[7].Value = li.Precision;
|
|||
|
oRow.Cells[8].Value = li.Scale;
|
|||
|
if (li.IsDefaultValueRequired)
|
|||
|
{
|
|||
|
oRow.Cells[6].Style.ForeColor = Color.Blue;
|
|||
|
oRow.Cells[6].Style.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold);
|
|||
|
}
|
|||
|
grdList.Rows[RowIndex].Tag = li;
|
|||
|
RowIndex++;
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
private void checkBox1_CheckedChanged(object sender, EventArgs e)
|
|||
|
{
|
|||
|
foreach (ListViewItem li in lsvSourceList.Items)
|
|||
|
li.Checked = checkBox1.Checked;
|
|||
|
}
|
|||
|
|
|||
|
private void button1_Click(object sender, EventArgs e)
|
|||
|
{
|
|||
|
Clipboard.SetText(rtbText.Text);
|
|||
|
}
|
|||
|
|
|||
|
private void ExecuteQuery(string sQuery)
|
|||
|
{
|
|||
|
try
|
|||
|
{
|
|||
|
SqlConnection conn = new SqlConnection(_destinationConnetionString);
|
|||
|
sQuery = sQuery.Replace("GO", "");
|
|||
|
SqlCommand cmd = new SqlCommand(sQuery, conn);
|
|||
|
conn.Open();
|
|||
|
cmd.ExecuteNonQuery();
|
|||
|
conn.Close();
|
|||
|
}
|
|||
|
catch (Exception e)
|
|||
|
{
|
|||
|
Console.WriteLine("exception occured while creating table:" + e.Message + "\t" + e.GetType());
|
|||
|
}
|
|||
|
}
|
|||
|
private void btnCreateScript_Click(object sender, EventArgs e)
|
|||
|
{
|
|||
|
try
|
|||
|
{
|
|||
|
//primary key
|
|||
|
DataTable dtSource = GePrimaryKeyList(EnumTargetType.Source);
|
|||
|
DataTable dtDestination = GePrimaryKeyList(EnumTargetType.Destination);
|
|||
|
|
|||
|
//foreign key
|
|||
|
DataTable dtFKSource = GeForeignKeyList(EnumTargetType.Source);
|
|||
|
DataTable dtFKDestination = GeForeignKeyList(EnumTargetType.Destination);
|
|||
|
|
|||
|
//default key
|
|||
|
DataTable dtDefaultKeyDestination = GetDefaultConstraint(EnumTargetType.Destination);
|
|||
|
|
|||
|
StringBuilder sql = new StringBuilder();
|
|||
|
StringBuilder errorCheckerMessage = new StringBuilder();
|
|||
|
bool isAllDfGiven = false;
|
|||
|
|
|||
|
_oTableLists = new List<TableList>();
|
|||
|
foreach (DataGridViewRow grd in grdList.Rows)
|
|||
|
{
|
|||
|
TableList item = (TableList)grd.Tag;
|
|||
|
item.DefaultValue = grd.Cells[5].Value.ToString();
|
|||
|
_oTableLists.Add(item);
|
|||
|
}
|
|||
|
|
|||
|
foreach (var item in _oTableLists)
|
|||
|
{
|
|||
|
if (item.IsDefaultValueRequired)
|
|||
|
{
|
|||
|
if (String.IsNullOrEmpty(item.DefaultValue))
|
|||
|
{
|
|||
|
isAllDfGiven = true;
|
|||
|
errorCheckerMessage.AppendFormat("Table: {0}, Col Name: {1}", item.TableName, item.ColumnName);
|
|||
|
errorCheckerMessage.AppendFormat("\r\n");
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
if (isAllDfGiven == true)
|
|||
|
{
|
|||
|
StringBuilder errorMessage = new StringBuilder();
|
|||
|
errorMessage.AppendFormat("Default Values Required: ");
|
|||
|
errorMessage.AppendFormat("\r\n");
|
|||
|
errorMessage.AppendFormat(errorCheckerMessage.ToString());
|
|||
|
Form2 form = new Form2();
|
|||
|
form.ShowDialog(errorMessage.ToString());
|
|||
|
return;
|
|||
|
}
|
|||
|
|
|||
|
_dtIdentityColumns = GetIdentityColumnList(EnumTargetType.Source);
|
|||
|
List<string> _oTempCreateTableNames = _oTableLists.Where(x => x.ScriptType == EnumScriptType.CreateTable).Select(y => y.TableName).Distinct().ToList();
|
|||
|
List<string> _oTempAlterTableNames = _oTableLists.Where(x => x.ScriptType == EnumScriptType.AlterTable).Select(y => y.TableName).Distinct().ToList();
|
|||
|
List<string> _oTempAlterTableAlterColNames = _oTableLists.Where(x => x.ScriptType == EnumScriptType.AlterColumn).Select(y => y.TableName).Distinct().ToList();
|
|||
|
|
|||
|
//create table script
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat("-------------- Create Table ------------------------------------\r\n\r\n");
|
|||
|
foreach (var item in _oTempCreateTableNames)
|
|||
|
{
|
|||
|
var tempTable = _oTableLists.Where(x => x.TableName == item && x.ScriptType == EnumScriptType.CreateTable).ToList();
|
|||
|
|
|||
|
string pkCol = null;
|
|||
|
string pkConstraint = null;
|
|||
|
|
|||
|
foreach (DataRow dr in dtSource.Rows)
|
|||
|
{
|
|||
|
if (item.ToLower() == dr[0].ToString().ToLower())
|
|||
|
{
|
|||
|
pkCol = dr[1].ToString();
|
|||
|
pkConstraint = dr[2].ToString();
|
|||
|
}
|
|||
|
}
|
|||
|
sql.AppendFormat("CREATE TABLE [{0}]\r\n(\r\n", item);
|
|||
|
int i = 0;
|
|||
|
string snip = "";
|
|||
|
foreach (var row in tempTable)
|
|||
|
{
|
|||
|
snip = GetColumnSqlCREATE(row);
|
|||
|
sql.AppendFormat((i < tempTable.Count - 1) ? snip.ToString() : snip.ToString().TrimEnd(',', '\r', '\n'));
|
|||
|
++i;
|
|||
|
}
|
|||
|
if (pkCol != null)
|
|||
|
{
|
|||
|
var pkColumnExist = tempTable.Where(x => x.ColumnName.ToLower() == pkCol.ToLower()).Any();
|
|||
|
if (pkColumnExist == true)
|
|||
|
{
|
|||
|
sql.AppendFormat(",");
|
|||
|
sql.AppendFormat("\r\n");
|
|||
|
sql.AppendFormat("\t CONSTRAINT {0} PRIMARY KEY ({1})",
|
|||
|
pkConstraint, pkCol);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
sql.AppendFormat("\r\n)");
|
|||
|
sql.AppendFormat("\r\n");
|
|||
|
}
|
|||
|
|
|||
|
//Alter Table script
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat("-------------- Alter Table ------------------------------------\r\n\r\n");
|
|||
|
foreach (var item in _oTempAlterTableNames)
|
|||
|
{
|
|||
|
var tempTable = _oTableLists.Where(x => x.TableName == item && x.ScriptType == EnumScriptType.AlterTable).ToList();
|
|||
|
string pkCol = null;
|
|||
|
string pkConstraint = null;
|
|||
|
foreach (DataRow dr in dtSource.Rows)
|
|||
|
{
|
|||
|
if (item.ToLower() == dr[0].ToString().ToLower())
|
|||
|
{
|
|||
|
pkCol = dr[1].ToString();
|
|||
|
pkConstraint = dr[2].ToString();
|
|||
|
}
|
|||
|
}
|
|||
|
sql.AppendFormat("ALTER TABLE [{0}]\r\n ADD", item);
|
|||
|
int i = 0;
|
|||
|
string snip = "";
|
|||
|
foreach (var row in tempTable)
|
|||
|
{
|
|||
|
snip = GetColumnSqlALTER(row);
|
|||
|
sql.AppendFormat((i < tempTable.Count - 1) ? snip : snip.Substring(0, snip.LastIndexOf(','))
|
|||
|
+ ";"
|
|||
|
+ snip.Substring(snip.LastIndexOf(',') + 1));
|
|||
|
++i;
|
|||
|
}
|
|||
|
if (pkCol != null)
|
|||
|
{
|
|||
|
var pkColumnAlreadyExist = dtDestination.AsEnumerable().Where(x => x[0].ToString().ToLower() == item.ToLower()).Any();
|
|||
|
var pkColumnExist = dtDestination.AsEnumerable().Where(x => x[0].ToString().ToLower() == item.ToLower()
|
|||
|
&& x[1].ToString().ToLower() == pkCol.ToLower()).Any();
|
|||
|
if (pkColumnAlreadyExist == false && pkColumnExist == false)
|
|||
|
{
|
|||
|
var text = sql.ToString().Substring(0, sql.ToString().LastIndexOf(';'))
|
|||
|
+ ","
|
|||
|
+ sql.ToString().Substring(sql.ToString().LastIndexOf(';') + 1);
|
|||
|
sql = new StringBuilder();
|
|||
|
sql.AppendFormat(text);
|
|||
|
// sql.AppendFormat("\r\n");
|
|||
|
sql.AppendFormat("CONSTRAINT {0} PRIMARY KEY ({1})",
|
|||
|
pkConstraint, pkCol);
|
|||
|
sql.AppendFormat(";");
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
sql.AppendFormat("\r\n");
|
|||
|
sql.AppendFormat("\r\n");
|
|||
|
}
|
|||
|
|
|||
|
//Alter col script
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat("-------------- Alter Column ------------------------------------\r\n\r\n");
|
|||
|
foreach (var item in _oTempAlterTableAlterColNames)
|
|||
|
{
|
|||
|
var tempTable = _oTableLists.Where(x => x.TableName == item && x.ScriptType == EnumScriptType.AlterColumn).ToList();
|
|||
|
|
|||
|
string pkCol = null;
|
|||
|
string pkConstraint = null;
|
|||
|
foreach (DataRow dr in dtSource.Rows)
|
|||
|
{
|
|||
|
if (item.ToLower() == dr[0].ToString().ToLower())
|
|||
|
{
|
|||
|
pkCol = dr[1].ToString();
|
|||
|
pkConstraint = dr[2].ToString();
|
|||
|
}
|
|||
|
}
|
|||
|
int i = 0;
|
|||
|
foreach (var row in tempTable)
|
|||
|
{
|
|||
|
//update if convert to null to not null
|
|||
|
if (row.AllowNull.ToLower() == "no")
|
|||
|
{
|
|||
|
if (row.ColumnName.ToLower() == "userid" || row.ColumnName.ToLower() == "createdby"
|
|||
|
|| row.ColumnName.ToLower() == "payrolltypeid" ||
|
|||
|
row.ColumnName.ToLower() == "createddate")
|
|||
|
{
|
|||
|
if (row.IsDefaultValueRequired || !String.IsNullOrEmpty(row.DefaultValue))
|
|||
|
{
|
|||
|
row.DefaultValue = DefaultValueSet(row.DefaultValue, row.ColumnName);
|
|||
|
|
|||
|
|
|||
|
sql.AppendFormat("UPDATE {0} SET {1}={2} WHERE {3} IS NULL ",
|
|||
|
row.TableName,
|
|||
|
row.ColumnName, row.ColumnName.ToLower() == "createddate" ? (row.DefaultValue.ToLower() == "getdate()" ? row.DefaultValue : "'" + row.DefaultValue + "'") : row.DefaultValue, row.ColumnName);
|
|||
|
sql.AppendFormat("\r\n");
|
|||
|
}
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
if (row.IsDefaultValueRequired || !String.IsNullOrEmpty(row.DefaultValue))
|
|||
|
{
|
|||
|
row.DefaultValue = DefValueBracesCheck(row.DefaultValue);
|
|||
|
|
|||
|
if (row.DataType.ToLower() == "int" || row.DataType.ToLower() == "money" || row.DataType.ToLower() == "numeric" ||
|
|||
|
row.DataType.ToLower() == "decimal" || row.DefaultValue == "tinyint")
|
|||
|
{
|
|||
|
var fkForeignKeyExist = dtFKDestination.AsEnumerable().Where(x => x[1].ToString().ToLower() == item.ToLower() && x[2].ToString().ToLower() == row.ColumnName.ToLower()).Any();
|
|||
|
if (fkForeignKeyExist == true)
|
|||
|
{
|
|||
|
sql.AppendFormat("UPDATE {0} SET {1}=1 WHERE {2} IS NULL ",
|
|||
|
row.TableName,
|
|||
|
row.ColumnName, row.ColumnName);
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
sql.AppendFormat("UPDATE {0} SET {1}=0 WHERE {2} IS NULL ",
|
|||
|
row.TableName,
|
|||
|
row.ColumnName, row.ColumnName);
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
if (row.DataType.ToLower() == "bit" || row.DataType.ToLower() == "smallint")
|
|||
|
{
|
|||
|
sql.AppendFormat("UPDATE {0} SET {1}=0 WHERE {2} IS NULL ",
|
|||
|
row.TableName,
|
|||
|
row.ColumnName, row.ColumnName);
|
|||
|
}
|
|||
|
sql.AppendFormat("\r\n");
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
ExistingDefaultConstraintCheck(dtDefaultKeyDestination, sql, row);
|
|||
|
|
|||
|
sql.AppendFormat("ALTER TABLE [{0}] ALTER COLUMN [{1}] [{2}] {3} {4} {5} ",
|
|||
|
row.TableName,
|
|||
|
row.ColumnName,
|
|||
|
row.DataType,
|
|||
|
(HasLength(row.DataType)) ? "(" + row.Length.ToString() + ")" : string.Empty,
|
|||
|
(HasPrecisionAndScale(row.DataType)) ? ((row.Precision != null && row.Scale != null) ? "(" + row.Precision + "," + row.Scale + ")" : string.Empty) : string.Empty,
|
|||
|
(row.AllowNull.ToLower() == "yes") ? "NULL" : "NOT NULL"
|
|||
|
);
|
|||
|
sql.AppendFormat(";\r\n");
|
|||
|
|
|||
|
//def value append
|
|||
|
DefaultValueAppendAlterColumn(row, sql);
|
|||
|
|
|||
|
++i;
|
|||
|
}
|
|||
|
if (pkCol != null)
|
|||
|
{
|
|||
|
var pkAlreadyColumnExist = dtDestination.AsEnumerable().Where(x => x[0].ToString().ToLower() == item.ToLower()).Any();
|
|||
|
var pkColumnExist = dtDestination.AsEnumerable().Where(x => x[0].ToString().ToLower() == item.ToLower()
|
|||
|
&& x[1].ToString().ToLower() == pkCol.ToLower()).Any();
|
|||
|
if (pkAlreadyColumnExist == false && pkColumnExist == false)
|
|||
|
{
|
|||
|
sql.AppendFormat("ALTER TABLE [{0}] ADD CONSTRAINT [{1}] PRIMARY KEY ({2})",
|
|||
|
item, pkConstraint, pkCol);
|
|||
|
sql.AppendFormat(";");
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
sql.AppendFormat("\r\n");
|
|||
|
sql.AppendFormat("\r\n");
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
//foreign key
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat("-------------- Foreign key ------------------------------------\r\n\r\n");
|
|||
|
ForeignKeyCreate(dtFKSource, sql, dtFKDestination);
|
|||
|
|
|||
|
|
|||
|
#region Misc script
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat("update users set usertype = 0 where userid in ( -9,-8)");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat("update userrole set EVENTDATE ='1 Jan 2023'");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat("update employee set persontype =0 where persontype is null");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"CREATE VIEW BankInformation AS
|
|||
|
SELECT employeeid, bn.NAME BANK, e.ACCOUNTNO FROM EMPLOYEE e, BRANCHES brn, BANKS bn
|
|||
|
WHERE e.BRANCHID = brn.BRANCHID
|
|||
|
AND brn.BANKID = bn.BANKID
|
|||
|
GO");
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"CREATE VIEW VW_EMPDigitalServiceBook AS
|
|||
|
SELECT E.EMPLOYEEID, E.EMPLOYEENO, E.BENGALINAME AS NAME, E.FATHERNAME, E.MOTHERNAME, ES.NAME AS SPOUSENAME, E.JOININGDATE, E.EMPLOYEESTATUS,
|
|||
|
DES.NAMEINBANGLA AS DESIGNATION, EC.PARMANENTADDRESS AS PARMANENTADDRESS, EC.PRESENTADDRESS AS PRESENTADDRESS, EC.PERMANENTPOSTOFFICE AS POSTOFFICE,
|
|||
|
EC.PERMANENTPOSTCODENO AS POSTCODENO, EC.PERMANENTVILLAGE AS VILLAGE, EC.PERMANENTROADNO AS ROADNO,
|
|||
|
EC.PERMANENTWARDNO AS WARDNO, E.BIRTHDATE AS BIRTHDATE, E.PHOTOPATH AS PHOTO, E.NATIONALID AS NIDNO, E.HEIGHT AS HEIGHT, E.BLOODGROUP AS BLOODGROUP,
|
|||
|
E.EMPSIGNATURE AS EMPSIGNATURE, LM.EMPSIGNATURE AS LMSIGNATURE, LMDES.NAMEINBANGLA AS LMDESIGNATION, EL.DESCRIPTION AS EDUCATIONLEVEL
|
|||
|
|
|||
|
FROM EMPLOYEE E
|
|||
|
LEFT JOIN EMPCONTACT EC ON E.EMPLOYEEID = EC.EMPLOYEEID
|
|||
|
LEFT JOIN DESIGNATION DES ON E.DEPARTMENTID = DES.DESIGNATIONID
|
|||
|
LEFT JOIN DISTRICT DIS ON DIS.DISTRICTID = EC.PARMANENTDISTRICTID
|
|||
|
LEFT JOIN THANA T ON T.THANAID = EC.PARMANENTTHANAID
|
|||
|
LEFT JOIN EMPSPOUSE ES ON E.EMPLOYEEID = ES.EMPLOYEEID
|
|||
|
LEFT JOIN EMPLOYEE LM ON E.LINEMANAGERID = E.EMPLOYEEID
|
|||
|
LEFT JOIN DESIGNATION LMDES ON LMDES.DESIGNATIONID = LM.DESIGNATIONID
|
|||
|
LEFT JOIN EMPACADEMIC EA ON E.EMPLOYEEID = EA.EMPLOYEEID
|
|||
|
LEFT JOIN EDUCATIONLEVEL EL ON EA.EDUCATIONLEVELID = EL.EDUCATIONLEVELID
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"CREATE VIEW VW_EmployeeAcademicInfo as SELECT e.employeeId AS EmployeeId, e.employeeNo AS EmployeeNo, e.name AS EmployeeName, a.institutename AS InstituteName,
|
|||
|
(SELECT description FROM EDUCATIONTYPE WHERE a.EDUCATIONTYPEID = EDUCATIONTYPEID) AS EducationType,
|
|||
|
(SELECT description FROM EDUCATIONLEVEL WHERE a.educationlevelId = educationlevelId) AS EducationLevel,
|
|||
|
(SELECT description FROM DISCIPLINE WHERE a.disciplineId = disciplineId) AS Discipline,
|
|||
|
(SELECT name FROM INSTITUTION WHERE a.institutionid=INSTITUTIONID) AS Institute,
|
|||
|
a.passingYear AS PassingYear,
|
|||
|
(SELECT DESCRIPTION FROM RESULTTYPE WHERE RESULTTYPEID=a.resulttypeid) AS ResultType
|
|||
|
FROM EMPACADEMIC a LEFT JOIN EMPLOYEE e ON a.EMPLOYEEID=e.EMPLOYEEID
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"CREATE VIEW VW_EMPLOYEEBASIC
|
|||
|
AS Select E.EmployeeId,E.EMPLOYEENO,E.NAME,E.BASICSALARY,E.GrossSalary,E.TAXAMOUNT, E.Fathername, occf.Description AS FatherOccupation,
|
|||
|
occm.Description AS MotherOccupation, E.MotherName, E.PhotoPath AS Photo,
|
|||
|
( case E.GENDER
|
|||
|
When 1 Then 'Male'
|
|||
|
When 2 Then 'Female'
|
|||
|
When 3 Then 'Both'
|
|||
|
Else 'None'
|
|||
|
End)As Gender,
|
|||
|
E.BIRTHDATE, E.BIRTHPlace, E.TINNO,E.JOININGDATE,E.EMAILADDRESS, Ca.DESCRIPTION as Category,L.DESCRIPTION as Location,
|
|||
|
(Case E.STATUS
|
|||
|
When 1 Then 'Active'
|
|||
|
When 2 Then 'InActive'
|
|||
|
Else 'Regardless'
|
|||
|
End) As Status,
|
|||
|
|
|||
|
(case dept5.tire
|
|||
|
when 5 then dept1.DESCRIPTION
|
|||
|
when 4 then dept2.DESCRIPTION
|
|||
|
when 3 then dept3.DESCRIPTION
|
|||
|
when 2 then dept4.DESCRIPTION
|
|||
|
when 1 then dept5.DESCRIPTION
|
|||
|
Else ''
|
|||
|
End) As Division,
|
|||
|
|
|||
|
(case dept5.tire
|
|||
|
when 5 then dept1.DEPARTMENTID
|
|||
|
when 4 then dept2.DEPARTMENTID
|
|||
|
when 3 then dept3.DEPARTMENTID
|
|||
|
when 2 then dept4.DEPARTMENTID
|
|||
|
when 1 then dept5.DEPARTMENTID
|
|||
|
End) As DivisionID,
|
|||
|
|
|||
|
case dept5.tire
|
|||
|
when 5 THEN dept2.DESCRIPTION
|
|||
|
when 4 then dept3.DESCRIPTION
|
|||
|
when 3 then dept4.DESCRIPTION
|
|||
|
when 2 then dept5.DESCRIPTION
|
|||
|
Else ''
|
|||
|
End As Company,
|
|||
|
|
|||
|
(case dept5.tire
|
|||
|
when 5 THEN dept2.DEPARTMENTID
|
|||
|
when 4 then dept3.DEPARTMENTID
|
|||
|
when 3 then dept4.DEPARTMENTID
|
|||
|
when 2 then dept5.DEPARTMENTID
|
|||
|
End) As CompanyID,
|
|||
|
|
|||
|
(case dept5.tire
|
|||
|
when 5 then dept3.DESCRIPTION
|
|||
|
when 4 then dept4.DESCRIPTION
|
|||
|
when 3 then dept5.DESCRIPTION
|
|||
|
when 2 then ''
|
|||
|
Else ''
|
|||
|
End) As Department,
|
|||
|
|
|||
|
(case dept5.tire
|
|||
|
when 5 then dept3.DEPARTMENTID
|
|||
|
when 4 then dept4.DEPARTMENTID
|
|||
|
when 3 then dept5.DEPARTMENTID
|
|||
|
End) As DepartmentID,
|
|||
|
|
|||
|
|
|||
|
(case dept5.tire
|
|||
|
when 5 then dept4.DESCRIPTION
|
|||
|
when 4 then dept5.DESCRIPTION
|
|||
|
when 3 then ''
|
|||
|
when 2 then ''
|
|||
|
Else ''
|
|||
|
End) As Section,
|
|||
|
|
|||
|
(case dept5.tire
|
|||
|
when 5 then dept4.DEPARTMENTID
|
|||
|
when 4 then dept5.DEPARTMENTID
|
|||
|
End) As SectionID,
|
|||
|
|
|||
|
|
|||
|
(case dept5.tire
|
|||
|
when 5 then dept5.DESCRIPTION
|
|||
|
when 4 then ''
|
|||
|
when 3 then ''
|
|||
|
when 2 then ''
|
|||
|
Else ''
|
|||
|
End) As SubSection,
|
|||
|
|
|||
|
(case dept5.tire
|
|||
|
when 5 then dept5.DEPARTMENTID
|
|||
|
End) As SubSectionID,
|
|||
|
|
|||
|
Deg.NAME as DESIGNATION,Gr.DESCRIPTION as GRADE, R.Name AS RELIGION,
|
|||
|
(case E.MARITALSTATUSID
|
|||
|
When 1 Then 'Married'
|
|||
|
When 2 Then 'Unmarried'
|
|||
|
When 3 Then 'Divorced'
|
|||
|
When 4 Then 'Widow'
|
|||
|
Else 'None'
|
|||
|
End) As MaritalStatus ,
|
|||
|
E.MOBILENO,E.VendorCode,E.DATEOFCONFIRMATION,E.NATIONALID,E.PassPortNo,E.PhotoPath,E.bloodgroup, lmemp.EMPLOYEEID AS LineManagerID,
|
|||
|
lmemp.EmployeeNo AS LineManagerNo,lmemp.Name AS LineManagerName,lmDeg.Name AS LineManagerDes,
|
|||
|
|
|||
|
(case lmDEp.tire
|
|||
|
when 4 then lmdept1.DESCRIPTION
|
|||
|
when 3 then lmdept2.DESCRIPTION
|
|||
|
when 2 then lmdept3.DESCRIPTION
|
|||
|
when 1 then lmDEp.DESCRIPTION
|
|||
|
Else ''
|
|||
|
End) As lmDivision,
|
|||
|
|
|||
|
(case lmDEp.tire
|
|||
|
when 4 THEN lmdept1.DEPARTMENTID
|
|||
|
when 3 then lmdept2.DEPARTMENTID
|
|||
|
when 2 THEN lmdept3.DEPARTMENTID
|
|||
|
when 1 then lmDEp.DEPARTMENTID
|
|||
|
End) As lmDivisionID,
|
|||
|
|
|||
|
case lmDEp.tire
|
|||
|
when 4 THEN lmdept2.DESCRIPTION
|
|||
|
when 3 then lmdept3.DESCRIPTION
|
|||
|
when 2 then lmDEp.DESCRIPTION
|
|||
|
Else ''
|
|||
|
End As lmDepartment,
|
|||
|
|
|||
|
(case lmDEp.tire
|
|||
|
when 4 then lmdept2.DepartmentID
|
|||
|
when 3 then lmdept3.DepartmentID
|
|||
|
when 2 then lmDEp.DepartmentID
|
|||
|
End) As lmDepartmentID,
|
|||
|
|
|||
|
(case lmDEp.tire
|
|||
|
when 4 then lmdept3.DESCRIPTION
|
|||
|
when 3 then lmDEp.DESCRIPTION
|
|||
|
when 2 then ''
|
|||
|
Else ''
|
|||
|
End) As lmUnit,
|
|||
|
|
|||
|
(case lmDEp.tire
|
|||
|
when 4 then lmdept3.DepartmentID
|
|||
|
when 3 then lmDEp.DepartmentID
|
|||
|
End) As lmUnitID,
|
|||
|
|
|||
|
|
|||
|
(case lmDEp.tire
|
|||
|
when 4 then lmDEp.DESCRIPTION
|
|||
|
when 3 then ''
|
|||
|
when 2 then ''
|
|||
|
Else ''
|
|||
|
End) As lmSubUnit,
|
|||
|
|
|||
|
(case lmDEp.tire
|
|||
|
when 4 then lmDEp.DepartmentID
|
|||
|
End) As lmSubUnitID,
|
|||
|
|
|||
|
(case E.IsConfirmed
|
|||
|
When 0 Then 'Probetionary'
|
|||
|
When 1 Then 'Confirmed'
|
|||
|
Else 'Regardless'
|
|||
|
End)As EmpStatus,
|
|||
|
cg.Code AS costcenter, nt.DESCRIPTION AS NATIONALITY,BK.NAME Bank,BR.NAME Branch,BKOUT.NAME OUTPayBank,BROUT.NAME OUTPayBranch, E.ACCOUNTNO,E.OutPayAccountNo
|
|||
|
|
|||
|
from Employee E
|
|||
|
Left outer join CATEGORY Ca on E.CATEGORYID = Ca.CATEGORYID
|
|||
|
|
|||
|
|
|||
|
LEFT JOIN DEPARTMENT dept5 ON dept5.DEPARTMENTID = E.DEPARTMENTID
|
|||
|
LEFT JOIN DEPARTMENT dept4 ON dept4.DEPARTMENTID = dept5.PARENTID
|
|||
|
LEFT JOIN DEPARTMENT dept3 ON dept3.DEPARTMENTID = dept4.PARENTID
|
|||
|
LEFT JOIN DEPARTMENT dept2 ON dept2.DEPARTMENTID = dept3.PARENTID
|
|||
|
LEFT JOIN DEPARTMENT dept1 ON dept1.DEPARTMENTID = dept2.PARENTID
|
|||
|
|
|||
|
|
|||
|
Left outer join DESIGNATION Deg on E.DESIGNATIONID = Deg.DESIGNATIONID
|
|||
|
Left outer join GRADES Gr on E.GRADEID = Gr.GRADEID
|
|||
|
Left Outer Join LOCATION L on E.LOCATIONID = L.LOCATIONID
|
|||
|
Left Outer Join RELIGION R on E.RELIGIONID = R.RELIGIONID
|
|||
|
LEFT OUTER JOIN EMPCOSTCENTER ec ON ec.EMPLOYEEID = e.EMPLOYEEID AND ec.CURRENTCC = 1
|
|||
|
LEFT OUTER JOIN CRG cg ON cg.CRGID = ec.COSTCENTERID
|
|||
|
LEFT OUTER JOIN NATIONALITY nt ON nt.NATIONALITYID = e.NATIONALITYID
|
|||
|
LEFT OUTER JOIN OCCUPATION occf ON occf.OCCUPATIONID = e.FATHEROCCUPATIONID
|
|||
|
LEFT OUTER JOIN OCCUPATION occm ON occm.OCCUPATIONID = e.MOTHEROCCUPATIONID
|
|||
|
LEFT OUTER JOIN EMPLOYEE lmemp ON lmemp.Employeeid = e.linemanagerid
|
|||
|
|
|||
|
LEFT OUTER JOIN ORGANEMPLOYEE orge ON orge.EMPLOYEEID = e.EMPLOYEEID
|
|||
|
LEFT OUTER JOIN ORGANOGRAM org ON org.ORGANOGRAMID = orge.NODEID
|
|||
|
LEFT OUTER JOIN ORGANEMPLOYEE orgel ON orgel.NODEID = org.PARENTID
|
|||
|
LEFT OUTER JOIN EMPLOYEE em ON em.EMPLOYEEID = orgel.EMPLOYEEID
|
|||
|
|
|||
|
Left outer join DESIGNATION lmDeg on lmemp.DESIGNATIONID = lmDeg.DESIGNATIONID
|
|||
|
Left JOIN DEPARTMENT lmDEp ON lmDEp.DEPARTMENTID = lmemp.DEPARTMENTID
|
|||
|
LEFT JOIN DEPARTMENT lmdept3 ON lmdept3.DEPARTMENTID = lmDEp.PARENTID
|
|||
|
LEFT JOIN DEPARTMENT lmdept2 ON lmdept2.DEPARTMENTID = lmdept3.PARENTID
|
|||
|
LEFT JOIN DEPARTMENT lmdept1 ON lmdept1.DEPARTMENTID = lmdept2.PARENTID
|
|||
|
LEFT OUTER JOIN Branches BR ON E.BRANCHID=BR.BRANCHID
|
|||
|
LEFT OUTER JOIN BANKS BK ON BK.BANKID=BR.BANKID
|
|||
|
LEFT OUTER JOIN Branches BROUT ON E.OUTPayBRANCHID=BROUT.BRANCHID
|
|||
|
LEFT OUTER JOIN BANKS BKOUT ON BKOUT.BANKID=BROUT.BANKID
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"CREATE VIEW VW_EmployeeChildrenInfo AS SELECT e.employeeid AS EmployeeId, e.employeeNo AS EmployeeNo, e.name AS EmployeeName, c.NAME,
|
|||
|
(
|
|||
|
CASE WHEN c.gender = 1 THEN 'Male'
|
|||
|
WHEN c.gender = 2 THEN 'Female'
|
|||
|
WHEN c.gender = 3 THEN 'Other'
|
|||
|
ELSE ''
|
|||
|
END
|
|||
|
) 'Gender', c.BIRTHDATE AS BirthDate,
|
|||
|
(
|
|||
|
CASE WHEN c.MARITALSTATUS = 1 THEN 'Married'
|
|||
|
WHEN c.MARITALSTATUS = 2 THEN 'Unmarried'
|
|||
|
WHEN c.MARITALSTATUS = 3 THEN 'Divorced'
|
|||
|
WHEN c.MARITALSTATUS = 4 THEN 'Widow'
|
|||
|
ELSE ''
|
|||
|
END
|
|||
|
) 'MaritalStatus', (SELECT description FROM OCCUPATION WHERE OCCUPATIONID=c.occupationId)AS Occupation, c.passportNo AS PassportNo,
|
|||
|
c.passportIssueDate AS PassportIssueDate, c.PassportExpDate AS PassportExpDate, c.nid,
|
|||
|
(SELECT description FROM EDUCATIONLEVEL WHERE EDUCATIONLEVELID = c.educationLevelId) AS EducationLevel, c.InsuranceId, c.InclusionDate
|
|||
|
FROM EMPCHILDREN c LEFT JOIN EMPLOYEE e ON c.employeeid = e.employeeId
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"CREATE VIEW VW_EmployeeContactInfo AS SELECT e.EMPLOYEEID AS EmployeeId, e.EMPLOYEENO AS EmployeeNo, e.NAME, c.PARMANENTADDRESS AS 'PermanentAddress',
|
|||
|
(SELECT name FROM DISTRICT WHERE DISTRICTID = c.PARMANENTDISTRICTID ) AS 'PermanentDistrict',
|
|||
|
(SELECT name FROM Thana WHERE ThanaId = c.PARMANENTTHANAID ) AS 'PermanentThana',
|
|||
|
c.PARMANENTTELEPHONE AS 'PermanentTelephone',
|
|||
|
c.PARMANENTMOBILE AS 'PermanentMobile',
|
|||
|
c.PRESENTADDRESS AS 'PresentAddress',
|
|||
|
(SELECT name FROM DISTRICT WHERE DISTRICTID = c.PresentDISTRICTID ) AS 'PresentDistrict',
|
|||
|
(SELECT name FROM Thana WHERE ThanaId = c.PresentTHANAID ) AS 'PresentThana',
|
|||
|
c.PresentTELEPHONE AS 'PresentTelephone',
|
|||
|
c.PRESENTMOBILE AS 'PresentMobile',
|
|||
|
c.EMERGENCYCONTACTADDRESS AS 'EmergencyContactAddress',
|
|||
|
c.EMERGENCYCONTACTPERSON AS 'EmergencyContactPerson',
|
|||
|
c.EMERGENCYTELEPHONE AS 'EmergencyTelephone'
|
|||
|
FROM EMPCONTACT c
|
|||
|
LEFT JOIN EMPLOYEE e ON e.EMPLOYEEID = c.EMPLOYEEID;
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"Create view VW_EmployeeGenderRatioData as
|
|||
|
WITH CTE AS
|
|||
|
(
|
|||
|
select d3.DepartmentID SectionId, d3.DESCRIPTION Section, d2.departmentId departmentId, d2.DESCRIPTION Department, d1.departmentId DivisionId, d1.DESCRIPTION Division
|
|||
|
from department d3
|
|||
|
LEFT JOIN department d2 ON d3.PARENTID=d2.DEPARTMENTID
|
|||
|
LEFT JOIN department d1 ON d2.PARENTID=d1.DEPARTMENTID
|
|||
|
)
|
|||
|
SELECT e.EMPLOYEEID AS EmployeeId, e.CATEGORYID AS categoryId, c.DESCRIPTION AS Category, e.DESIGNATIONID AS designationId, dg.NAME AS Designation,
|
|||
|
e.GRADEID AS GradeId, g.DESCRIPTION AS Grade, e.RELIGIONID AS ReligionId, r.NAME AS Religion, e.departmentId AS sectionId,
|
|||
|
dept.Section AS Section, dept.departmentId, dept.Department, dept.DivisionId, dept.Division,
|
|||
|
(
|
|||
|
CASE WHEN e.gender = 1 THEN 'Male'
|
|||
|
WHEN e.gender = 2 THEN 'Female'
|
|||
|
WHEN e.gender = 3 THEN 'Other'
|
|||
|
ELSE ''
|
|||
|
END
|
|||
|
) Gender
|
|||
|
FROM employee e LEFT JOIN CATEGORY c ON e.CATEGORYID=c.CATEGORYID
|
|||
|
LEFT JOIN DESIGNATION dg ON e.DESIGNATIONID=dg.DESIGNATIONID
|
|||
|
LEFT JOIN GRADES g ON e.GRADEID=g.GRADEID
|
|||
|
LEFT JOIN RELIGION r ON r.RELIGIONID=e.RELIGIONID
|
|||
|
LEFT JOIN CTE dept ON dept.sectionId=e.DEPARTMENTID
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"CREATE VIEW VW_EmployeeGeneralData AS SELECT e.EMPLOYEEID, e.EMPLOYEENO, e.FIRSTNAME, e.LASTNAME, e.name AS 'FullName', e.ExtraField1 AS 'EmployeeDName', e.JOININGDATE,
|
|||
|
e.BIRTHDATE,
|
|||
|
(SELECT name FROM DESIGNATION WHERE DESIGNATIONID = e.employeeid) AS 'Designation',
|
|||
|
(SELECT DESCRIPTION FROM GRADES WHERE GRADEID = e.employeeid) AS 'Grade',
|
|||
|
(
|
|||
|
CASE WHEN e.MARITALSTATUSID = 1 THEN 'Married'
|
|||
|
WHEN e.MARITALSTATUSID = 2 THEN 'Unmarried'
|
|||
|
WHEN e.MARITALSTATUSID = 3 THEN 'Divorced'
|
|||
|
WHEN e.MARITALSTATUSID = 4 THEN 'Widow'
|
|||
|
ELSE ''
|
|||
|
END
|
|||
|
) 'MaritalStatus',
|
|||
|
(
|
|||
|
CASE WHEN e.gender = 1 THEN 'Male'
|
|||
|
WHEN e.gender = 2 THEN 'Female'
|
|||
|
WHEN e.gender = 3 THEN 'Other'
|
|||
|
ELSE ''
|
|||
|
END
|
|||
|
) 'Gender',
|
|||
|
(
|
|||
|
CASE WHEN e.BLOODGROUP = 1 THEN 'A+'
|
|||
|
WHEN e.BLOODGROUP = 2 THEN 'A-'
|
|||
|
WHEN e.BLOODGROUP = 3 THEN 'B+'
|
|||
|
WHEN e.BLOODGROUP = 4 THEN 'B-'
|
|||
|
WHEN e.BLOODGROUP = 5 THEN 'O+'
|
|||
|
WHEN e.BLOODGROUP = 6 THEN 'O-'
|
|||
|
WHEN e.BLOODGROUP = 7 THEN 'AB+'
|
|||
|
WHEN e.BLOODGROUP = 8 THEN 'AB-'
|
|||
|
ELSE ''
|
|||
|
END
|
|||
|
) 'BloodGroup',
|
|||
|
|
|||
|
(SELECT description FROM CATEGORY c WHERE c.CATEGORYID = e.categoryid ) AS 'Category',
|
|||
|
(SELECT employeeNo+'-'+name FROM EMPLOYEE WHERE employeeid = e.lineManagerId) AS 'LineManager',
|
|||
|
e.emailAddress, e.mobileno,
|
|||
|
(SELECT name FROM RELIGION WHERE RELIGIONID = e.religionId) AS 'Religion',
|
|||
|
(SELECT description FROM NATIONALITY WHERE NATIONALITYID = e.nationalityId) AS NATIONALITY,
|
|||
|
e.geid AS 'EmpCode', e.NATIONALID AS 'NID', e.TINNO AS 'TIN', e.DRIVINGLICENCENO AS 'DrivingLicenceNo', e.BirthPlace AS 'BirthPlace',
|
|||
|
e.passportNo AS 'PassportNo', e.PASSPORTISSUEDATE AS 'PassportIssueDate', e.PASSPORTEXPDATE AS 'PassportExpireDate',
|
|||
|
(
|
|||
|
CASE WHEN e.extraField2 = 1 THEN 'Dhaka'
|
|||
|
WHEN e.extraField2 = 2 THEN 'Other'
|
|||
|
ELSE ''
|
|||
|
END
|
|||
|
) 'BaseStation',
|
|||
|
e.insuranceId AS 'InsuranceId', e.fatherName AS 'FatherName',
|
|||
|
(SELECT description FROM OCCUPATION WHERE OCCUPATIONID = e.fatherOccupationId) AS 'FatherOccupation',
|
|||
|
e.motherName AS 'MotherName',
|
|||
|
(SELECT description FROM OCCUPATION WHERE OCCUPATIONID = e.motherOccupationId) AS 'MotherOccupation',
|
|||
|
e.extraField3 AS 'TypeName', e.vendorCode AS 'VendorCode', e.extrafield4 AS 'MinValue', e.extrafield5 AS 'MaxValue'
|
|||
|
FROM EMPLOYEE e;
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"CREATE VIEW dbo.vw_EmployeeImportantInfo
|
|||
|
AS
|
|||
|
SELECT E.EmployeeID, E.EmployeeNo, E.Name, E.TINNO, E.JoiningDate, E.BasicSalary, e.GROSSSALARY, e.[STATUS], e.BloodGroup, G.GRADEID, IsNull(G.DESCRIPTION, '') AS GradeName,
|
|||
|
IsNULL(G.CODE, '') AS GCode, IsNull(G.SequenceNo, 0) AS SequenceNo, D .DESIGNATIONID, IsNUll(D .NAME, '') AS [Designation]
|
|||
|
, E.PaymentMode, 'PaymentModeName' = CASE WHEN E.PaymentMode = 1 THEN 'Cash' ELSE 'Bank' END, ISNULL(E.ACCOUNTNO, '') AS ACCOUNTNO, E.BRANCHID, ISNULL(BR.NAME, '')
|
|||
|
AS BranchName, BA.BANKID, ISNULL(Ba.NAME, '') AS BankName, E.OUTPAYACCOUNTNO, E.OUTPAYBRANCHID, ISNULL(BRO.Name, '') AS OutPayBranchName, BAO.BankID AS OUTPAYBANKID, ISNULL(BAO.NAME, '')
|
|||
|
AS OUTPAYBankName, E.CardID,
|
|||
|
(SELECT CardNumber
|
|||
|
FROM AccessCard
|
|||
|
WHERE AccessCardId = E.CardId) AS [RFNumber], e.NationalID, n.[DESCRIPTION] AS Nationality, e.EMAILADDRESS, e.MOBILENO, e.FATHERNAME, e.MOTHERNAME,
|
|||
|
e.BIRTHDATE, rl.NAME AS Religion, e.MARITALSTATUSID, e.GENDER AS GenderID, ec.PRESENTADDRESS, ec.PARMANENTADDRESS,
|
|||
|
ec.PERSONALTELEPHONE, d2.NAME AS ParmanentDistric, d3.NAME AS TempDistric,
|
|||
|
t1.NAME AS TempThana,ec.PERSONALEMAIL, ec.OFFICIALEMAIL, ec.EMERGENCYTELEPHONE, ec.EMERGENCYMOBILE, ec.FAX,
|
|||
|
t2.NAME AS ParmanentThana, e3.[DESCRIPTION] AS EducationLevel, e2.PASSINGYEAR, MIN(gs.GROSSSALARY) AS JoiningSalary, MIN(gs.EFFECTDATE) AS EffectedDate,
|
|||
|
e.PhotoPath, e.EMPSIGNATURE, 'Divission' = CASE WHEN dept5.tire = 5 THEN ISNULL(dept1.[DESCRIPTION], '') WHEN dept5.tire = 4 THEN ISNULL(dept2.[DESCRIPTION], '')
|
|||
|
WHEN dept5.tire = 3 THEN ISNULL(dept3.[DESCRIPTION], '') WHEN dept5.tire = 2 THEN ISNULL(dept4.[DESCRIPTION], '') WHEN dept5.tire = 1 THEN ISNULL(dept5.[DESCRIPTION], '') END,
|
|||
|
'DivissionID' = CASE WHEN dept5.tire = 5 THEN dept1.DEPARTMENTID WHEN dept5.tire = 4 THEN dept2.DEPARTMENTID WHEN dept5.tire = 3 THEN dept3.DEPARTMENTID WHEN dept5.tire = 2 THEN dept4.DEPARTMENTID WHEN
|
|||
|
dept5.tire = 1 THEN dept1.DEPARTMENTID END,
|
|||
|
'Unit' = CASE WHEN dept5.tire = 3 THEN ISNULL(dept3.[DESCRIPTION], '') WHEN dept5.tire = 2 THEN ISNULL(dept4.[DESCRIPTION], '')
|
|||
|
WHEN dept5.tire = 1 THEN ISNULL(dept5.[DESCRIPTION], '') END,
|
|||
|
'Department' = CASE WHEN dept5.tire = 5 THEN ISNULL(dept2.[DESCRIPTION], '') WHEN dept5.tire = 4 THEN ISNULL(dept3.[DESCRIPTION], '')
|
|||
|
WHEN dept5.tire = 3 THEN ISNULL(dept4.[DESCRIPTION], '') WHEN dept5.tire = 2 THEN ISNULL(dept5.[DESCRIPTION], '') END,
|
|||
|
'FunctionalUnit' = CASE WHEN dept5.tire = 3 THEN ISNULL(dept5.[DESCRIPTION], '') END,
|
|||
|
'DepartmentID' = CASE WHEN dept5.tire = 5 THEN dept2.DepartmentID WHEN dept5.tire = 4 THEN dept3.DepartmentID
|
|||
|
WHEN dept5.tire = 3 THEN dept4.DepartmentID WHEN dept5.tire = 2 THEN dept5.DepartmentID END,
|
|||
|
'Floor' = CASE WHEN dept5.tire = 5 THEN ISNULL(dept3.[DESCRIPTION], '') WHEN dept5.tire = 4 THEN ISNULL(dept4.[DESCRIPTION], '')
|
|||
|
WHEN dept5.tire = 3 THEN ISNULL(dept5.[DESCRIPTION], '') WHEN dept5.tire = 2 THEN '' END,
|
|||
|
'FloorID' = CASE WHEN dept5.tire = 5 THEN dept3.DepartmentID WHEN dept5.tire = 4 THEN dept4.DepartmentID WHEN dept5.tire = 3 THEN dept5.DepartmentID WHEN dept5.tire = 2 THEN '' END,
|
|||
|
'Section' = CASE WHEN dept5.tire = 5 THEN ISNULL(dept4.[DESCRIPTION], '') WHEN dept5.tire = 4 THEN ISNULL(dept5.[DESCRIPTION], '') WHEN dept5.tire = 3 THEN '' WHEN dept5.tire = 2 THEN '' END,
|
|||
|
'SectionID' = CASE WHEN dept5.tire = 5 THEN dept4.DepartmentID WHEN dept5.tire = 4 THEN dept5.DepartmentID WHEN dept5.tire = 3 THEN '' WHEN dept5.tire = 2 THEN '' END,
|
|||
|
'Line' = CASE WHEN dept5.tire = 5 THEN ISNULL(dept5.[DESCRIPTION], '') WHEN dept5.tire = 4 THEN '' WHEN dept5.tire = 3 THEN '' WHEN dept5.tire = 2 THEN '' END,
|
|||
|
'LineID' = CASE WHEN dept5.tire = 5 THEN dept5.DepartmentID WHEN dept5.tire = 4 THEN '' WHEN dept5.tire = 3 THEN '' WHEN dept5.tire = 2 THEN '' END
|
|||
|
FROM Employee E LEFT JOIN
|
|||
|
DESIGNATION D ON D .DESIGNATIONID = E.DESIGNATIONID LEFT JOIN
|
|||
|
Grades G ON E.GRADEID = G.GRADEID LEFT JOIN
|
|||
|
BRANCHES BR ON E.BRANCHID = BR.BRANCHID LEFT JOIN
|
|||
|
BANKS BA ON BR.BANKID = BA.BANKID LEFT JOIN
|
|||
|
BRANCHES BRO ON E.OUTPAYBRANCHID = BRO.BRANCHID LEFT JOIN
|
|||
|
BANKS BAO ON BRO.BANKID = BAO.BANKID LEFT JOIN
|
|||
|
RELIGION AS rl ON rl.RELIGIONID = e.RELIGIONID LEFT JOIN
|
|||
|
EMPCONTACT AS Ec ON ec.EMPLOYEEID = e.EMPLOYEEID LEFT JOIN
|
|||
|
DISTRICT AS d2 ON d2.DISTRICTID = ec.PARMANENTDISTRICTID LEFT JOIN
|
|||
|
DISTRICT AS d3 ON d3.DISTRICTID = ec.PRESENTDISTRICTID LEFT JOIN
|
|||
|
THANA AS t1 ON t1.THANAID = ec.PRESENTTHANAID LEFT JOIN
|
|||
|
THANA AS t2 ON t2.THANAID = ec.PARMANENTTHANAID LEFT JOIN
|
|||
|
(SELECT *
|
|||
|
FROM (SELECT EmployeeID, ROW_NUMBER() OVER (PARTITION BY EMPLOYEEID
|
|||
|
ORDER BY EMPLOYEEID, LastLevel DESC, PassingYear DESC) Sl, PassingYear, LastLevel, EDUCATIONLEVELID
|
|||
|
FROM EMPACADEMIC
|
|||
|
GROUP BY EMPLOYEEID, LastLevel, PassingYear, EDUCATIONLEVELID) a
|
|||
|
WHERE Sl = 1) AS e2 ON e2.EMPLOYEEID = e.EMPLOYEEID LEFT JOIN
|
|||
|
GRADESALARYASSIGNMENT AS gs ON gs.EMPLOYEEID = e.EMPLOYEEID LEFT JOIN
|
|||
|
EDUCATIONLEVEL AS e3 ON e3.EDUCATIONLEVELID = e2.EDUCATIONLEVELID LEFT JOIN
|
|||
|
NATIONALITY AS n ON n.NATIONALITYID = e.NATIONALITYID LEFT JOIN
|
|||
|
DEPARTMENT dept5 ON dept5.DEPARTMENTID = E.DEPARTMENTID LEFT JOIN
|
|||
|
DEPARTMENT dept4 ON dept4.DEPARTMENTID = dept5.PARENTID LEFT JOIN
|
|||
|
DEPARTMENT dept3 ON dept3.DEPARTMENTID = dept4.PARENTID LEFT JOIN
|
|||
|
DEPARTMENT dept2 ON dept2.DEPARTMENTID = dept3.PARENTID LEFT JOIN
|
|||
|
DEPARTMENT dept1 ON dept1.DEPARTMENTID = dept2.PARENTID
|
|||
|
|
|||
|
GROUP BY E.EmployeeID, E.EmployeeNo, E.Name, E.TINNO, E.JoiningDate, E.BasicSalary, e.GROSSSALARY, e.[STATUS], e.BloodGroup, G.GRADEID, G.DESCRIPTION, G.CODE, G.SequenceNo,
|
|||
|
D .DESIGNATIONID, D .NAME, E.PaymentMode, E.ACCOUNTNO, E.BRANCHID, BR.NAME, BA.BANKID, BA.NAME, E.OUTPAYACCOUNTNO, E.OUTPAYBRANCHID, BRO.Name, BAO.BankID, BAO.NAME, E.CardID,
|
|||
|
e.NationalID, n.[DESCRIPTION], e.EMAILADDRESS, e.MOBILENO, e.FATHERNAME, e.MOTHERNAME, e.BIRTHDATE, rl.NAME, e.MARITALSTATUSID, e.GENDER,
|
|||
|
ec.PRESENTADDRESS, ec.PARMANENTADDRESS,
|
|||
|
ec.PERSONALTELEPHONE, d2.NAME, d3.NAME, t1.NAME, ec.PERSONALEMAIL, ec.OFFICIALEMAIL, ec.EMERGENCYTELEPHONE, ec.EMERGENCYMOBILE, ec.FAX,
|
|||
|
t2.NAME, e3.[DESCRIPTION], e2.PASSINGYEAR, e.PhotoPath, e.EMPSIGNATURE, dept1.TIRE, dept1.[DESCRIPTION], dept1.DepartmentID, dept2.TIRE, dept2.[DESCRIPTION],
|
|||
|
dept2.DepartmentID, dept3.TIRE, dept3.[DESCRIPTION], dept3.DepartmentID, dept4.TIRE, dept4.[DESCRIPTION], dept4.DepartmentID, dept5.TIRE,
|
|||
|
dept5.[DESCRIPTION], dept5.DepartmentID
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"CREATE VIEW VW_EmployeeSpouseInfo as SELECT e.employeeid, e.employeeNo, e.Name AS 'EmployeeName', s.NAME AS 'SpouseName', ed.description AS 'EducationLevel',
|
|||
|
oc.DESCRIPTION AS 'Occupation', s.PASSPORTNO AS PassportNo, s.PASSPORTISSUEDATE AS 'PassportIssueDate', s.PASSPORTEXPDATE AS 'PassportExpDate',
|
|||
|
s.NID, s.InsuranceId, s.InclusionDate
|
|||
|
FROM EMPSPOUSE s LEFT JOIN EMPLOYEE e ON s.EMPLOYEEID=e.EMPLOYEEID
|
|||
|
LEFT JOIN EDUCATIONLEVEL ed ON s.EDUCATIONLEVELID=ed.EDUCATIONLEVELID
|
|||
|
LEFT JOIN OCCUPATION oc ON s.OCCUPATIONID=oc.OCCUPATIONID
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"create view VW_EmployeeSummaryData as
|
|||
|
select X.*,
|
|||
|
(
|
|||
|
case
|
|||
|
when X.age >= 20 and X.age <= 30 then '20 - 30'
|
|||
|
when X.age >= 31 and X.age <= 40 then '31 - 40'
|
|||
|
when X.age >= 41 and X.age <= 50 then '41 - 50'
|
|||
|
when X.age >= 51 then '50+'
|
|||
|
else 'Others'
|
|||
|
end
|
|||
|
) AgeGroup
|
|||
|
from
|
|||
|
(
|
|||
|
SELECT emp.name Name, dept.DESCRIPTION Department,sc.DESCRIPTION Section, dv.DESCRIPTION division, desg.NAME Designation, g.description Grade, cat.Description Category, region.description Region, zone.description Zone,
|
|||
|
(
|
|||
|
CASE WHEN emp.MARITALSTATUSID = 1 THEN 'Married'
|
|||
|
WHEN emp.MARITALSTATUSID = 2 THEN 'Unmarried'
|
|||
|
WHEN emp.MARITALSTATUSID = 3 THEN 'Divorced'
|
|||
|
WHEN emp.MARITALSTATUSID = 4 THEN 'Widow'
|
|||
|
ELSE ''
|
|||
|
END
|
|||
|
) 'MaritalStatus',
|
|||
|
(
|
|||
|
CASE WHEN emp.gender = 1 THEN 'Male'
|
|||
|
WHEN emp.gender = 2 THEN 'Female'
|
|||
|
WHEN emp.gender = 3 THEN 'Other'
|
|||
|
ELSE ''
|
|||
|
END
|
|||
|
) 'Gender',
|
|||
|
(
|
|||
|
CASE WHEN emp.BLOODGROUP = 1 THEN 'A+'
|
|||
|
WHEN emp.BLOODGROUP = 2 THEN 'A-'
|
|||
|
WHEN emp.BLOODGROUP = 3 THEN 'B+'
|
|||
|
WHEN emp.BLOODGROUP = 4 THEN 'B-'
|
|||
|
WHEN emp.BLOODGROUP = 5 THEN 'O+'
|
|||
|
WHEN emp.BLOODGROUP = 6 THEN 'O-'
|
|||
|
WHEN emp.BLOODGROUP = 7 THEN 'AB+'
|
|||
|
WHEN emp.BLOODGROUP = 8 THEN 'AB-'
|
|||
|
ELSE ''
|
|||
|
END
|
|||
|
) 'BloodGroup',
|
|||
|
|
|||
|
religion.NAME Religion,
|
|||
|
DATEDIFF(MONTH, emp.birthdate, GETDATE())/12 age
|
|||
|
|
|||
|
FROM EMPLOYEE emp
|
|||
|
LEFT JOIN DEPARTMENT dept ON emp.DEPARTMENTID = dept.DEPARTMENTID
|
|||
|
LEFT JOIN DEPARTMENT sc ON sc.DEPARTMENTID = dept.PARENTID
|
|||
|
LEFT JOIN DEPARTMENT dv ON dv.DEPARTMENTID = sc.PARENTID
|
|||
|
LEFT JOIN DESIGNATION desg ON emp.DESIGNATIONID = desg.DESIGNATIONID
|
|||
|
LEFT JOIN RELIGION religion ON emp.RELIGIONID = RELIGION.RELIGIONID
|
|||
|
LEFT JOIN CATEGORY cat ON emp.CATEGORYID = cat.CATEGORYID
|
|||
|
LEFT JOIN GRADES g ON emp.GRADEID = g.GRADEID
|
|||
|
LEFT JOIN LOCATION region on emp.LOCATIONID = region.LOCATIONID
|
|||
|
LEFT JOIN LOCATION zone on zone.LOCATIONID = region.parentId
|
|||
|
WHERE emp.STATUS=1
|
|||
|
) X
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"CREATE VIEW VW_EmployeeTrainingInfo as SELECT e.EMPLOYEEID AS EmployeeId, e.employeeNo AS EmployeeNo, e.NAME AS EmployeeName, t.name AS TrainingTitle, t.description AS Description,
|
|||
|
(SELECT name FROM TRAININGTYPE WHERE TRAININGTYPEID = t.trainingTypeId) AS TrainingType,
|
|||
|
(SELECT name FROM TRAINING WHERE TRAININGID = t.TRAININGID) AS NatureOfTraining,
|
|||
|
(SELECT name FROM INSTITUTION WHERE INSTITUTIONID=t.institutionId)AS Institution,
|
|||
|
t.trainingPlace AS TrainingPlace, t.fromDate AS FromDate, t.toDate AS ToDate
|
|||
|
FROM EMPTRAINING t LEFT JOIN EMPLOYEE e ON t.EMPLOYEEID = e.EMPLOYEEID
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"create Procedure ProfileComplitionPercentCalcuate
|
|||
|
@empId INT
|
|||
|
AS
|
|||
|
SET NOCOUNT ON;
|
|||
|
DECLARE @total INT = 0
|
|||
|
DECLARE @mobile VARCHAR(200), @NID VARCHAR(200), @Blood INT, @TIN VARCHAR(50)
|
|||
|
DECLARE @perAd VARCHAR(2000), @perD INT, @perThana INT, @perTel VARCHAR(100), @perMobile VARCHAR(100)
|
|||
|
DECLARE @pAd VARCHAR(2000), @pD INT, @pThana INT, @pTel VARCHAR(100), @pMobile VARCHAR(100)
|
|||
|
DECLARE @ePerson VARCHAR(100), @eAd VARCHAR(2000), @eTel VARCHAR(100)
|
|||
|
begin
|
|||
|
SELECT @mobile= e.MOBILENO,@NID= e.NATIONALID, @Blood= e.BLOODGROUP, @TIN= e.TINNO FROM EMPLOYEE e WHERE e.EMPLOYEEID=@empId
|
|||
|
IF isnull(@mobile, '') <> ''
|
|||
|
BEGIN
|
|||
|
SET @total = @total + 10
|
|||
|
END
|
|||
|
IF isnull(@NID, '') <> ''
|
|||
|
BEGIN
|
|||
|
SET @total = @total + 10
|
|||
|
END
|
|||
|
IF isnull(@Blood, 0) <> 0
|
|||
|
BEGIN
|
|||
|
SET @total = @total + 10
|
|||
|
END
|
|||
|
IF isnull(@TIN, '') <> ''
|
|||
|
BEGIN
|
|||
|
SET @total = @total + 10
|
|||
|
END
|
|||
|
|
|||
|
IF EXISTS (SELECT a.ACADEMICID FROM EMPACADEMIC a WHERE a.EMPLOYEEID=@empId)
|
|||
|
BEGIN
|
|||
|
SET @total = @total + 20
|
|||
|
END
|
|||
|
|
|||
|
IF EXISTS (SELECT e.empFileuploadid FROM empFileUpload e WHERE e.empid=@empId AND e.fileType=1)
|
|||
|
BEGIN
|
|||
|
SET @total = @total + 10
|
|||
|
END
|
|||
|
|
|||
|
SELECT @perAd= c.PARMANENTADDRESS, @perD= c.PARMANENTDISTRICTID, @perThana= c.PARMANENTTHANAID, @perTel= c.PARMANENTTELEPHONE, @perMobile = c.PARMANENTMOBILE FROM EMPCONTACT c WHERE c.EMPLOYEEID=@empId
|
|||
|
IF isnull(@perAd, '') <> ''
|
|||
|
AND isnull(@perD, 0) <> 0
|
|||
|
AND isnull(@perThana, 0) <> 0
|
|||
|
AND isnull(@perTel, '') <> ''
|
|||
|
AND isnull(@perMobile, '') <> ''
|
|||
|
BEGIN
|
|||
|
SET @total = @total + 10
|
|||
|
END
|
|||
|
|
|||
|
|
|||
|
SELECT @pAd= c.PRESENTADDRESS, @pD= c.PRESENTDISTRICTID, @pThana= c.PRESENTTHANAID, @pTel= c.PRESENTTELEPHONE, @pMobile = c.PRESENTMOBILE FROM EMPCONTACT c WHERE c.EMPLOYEEID=@empId
|
|||
|
IF isnull(@pAd, '') <> ''
|
|||
|
AND isnull(@pD, 0) <> 0
|
|||
|
AND isnull(@pThana, 0) <> 0
|
|||
|
AND isnull(@pTel, '') <> ''
|
|||
|
AND isnull(@pMobile, '') <> ''
|
|||
|
BEGIN
|
|||
|
SET @total = @total + 10
|
|||
|
END
|
|||
|
|
|||
|
SELECT @ePerson= c.EMERGENCYCONTACTPERSON, @eAd= c.EMERGENCYCONTACTADDRESS, @eTel= c.EMERGENCYTELEPHONE FROM EMPCONTACT c WHERE c.EMPLOYEEID=@empId
|
|||
|
IF isnull(@ePerson, '') <> ''
|
|||
|
AND isnull(@eAd, '') <> ''
|
|||
|
AND isnull(@eTel, '') <> ''
|
|||
|
BEGIN
|
|||
|
SET @total = @total + 10
|
|||
|
END
|
|||
|
|
|||
|
UPDATE EMPLOYEE SET ProfileComplitionPercent=@total WHERE EMPLOYEEID=@empId
|
|||
|
end
|
|||
|
GO
|
|||
|
");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"CREATE PROCEDURE [dbo].[sp_DashboardInformation] @ModEmployee smallint = 1, @ModLeave smallint = 0, @ModAttendance smallint = 0, @PayrollTypeID int = 1
|
|||
|
AS
|
|||
|
begin
|
|||
|
declare @LiveEmployee int=0,
|
|||
|
@NewJoiner int=0,
|
|||
|
@LeftEmployee int=0 ,
|
|||
|
@PostingMissing int=0,
|
|||
|
@ConfirmationWaiting int=0 ,
|
|||
|
@NextSalaryDate date,
|
|||
|
@ProfileComplitionPercent int=0,
|
|||
|
@ProfileRequest int=0,
|
|||
|
@LeaveinNextweek int=0,
|
|||
|
@PendingApproval int=0,
|
|||
|
@LongPending int=0,
|
|||
|
@RosterMissing int=0,
|
|||
|
@PresentDays int=0,
|
|||
|
@AbsentDays int=0,
|
|||
|
@WeekStart date=(select DATEADD(DAY, DATEDIFF(DAY, -1, GETDATE()) / 7 * 7, 5)),
|
|||
|
@WeekEnd date=(select DATEADD(DAY, DATEDIFF(DAY, -1, GETDATE()) / 7 * 7, 5))+6,
|
|||
|
@TableName NVARCHAR(128),
|
|||
|
@Sql NVARCHAR(max)='',
|
|||
|
@InsertSql NVARCHAR(max)=''
|
|||
|
|
|||
|
if @ModEmployee=1
|
|||
|
begin
|
|||
|
set @LiveEmployee=(select count(employeeid)
|
|||
|
from EMPLOYEE where status=1
|
|||
|
and PAYROLLTYPEID=@PayrollTypeID)
|
|||
|
set @NewJoiner=(select count(e.employeeid)
|
|||
|
from EMPLOYEE e
|
|||
|
where month(e.joiningdate)=month(getdate())
|
|||
|
AND year(e.joiningdate)=year(getdate()) and PAYROLLTYPEID=@PayrollTypeID)
|
|||
|
set @LeftEmployee=(select count(e.employeeid)
|
|||
|
from EMPLOYEE e
|
|||
|
where month(e.ENDOFCONTRACTDATE)=month(getdate())
|
|||
|
AND year(e.ENDOFCONTRACTDATE)=year(getdate())
|
|||
|
and PAYROLLTYPEID=@PayrollTypeID)
|
|||
|
set @PostingMissing=(select count(e.employeeid)
|
|||
|
from EMPLOYEE e
|
|||
|
where PAYROLLTYPEID=@PayrollTypeID
|
|||
|
AND (e.GRADEID is null OR e.DEPARTMENTID is null OR e.DESIGNATIONID is null OR e.locationid is null OR e.basicsalary=0 ))
|
|||
|
set @ConfirmationWaiting=(select count(e.employeeid)
|
|||
|
from EMPLOYEE e
|
|||
|
where e.ISCONFIRMED=0
|
|||
|
and dbo.fun_datediff_in_months( e.joiningdate, getdate())>=3
|
|||
|
and PAYROLLTYPEID=@PayrollTypeID) -- Window period 3 months
|
|||
|
set @NextSalaryDate=(select NEXTPAYPROCESSDATE
|
|||
|
from payrolltype
|
|||
|
where PAYROLLTYPEID=@PayrollTypeID)
|
|||
|
set @ProfileComplitionPercent=(select
|
|||
|
(select sum(ProfileComplitionPercent)
|
|||
|
from employee
|
|||
|
where status=1 and PAYROLLTYPEID=@PayrollTypeID)/
|
|||
|
(select count(employeeid)
|
|||
|
from employee where status=1
|
|||
|
and PAYROLLTYPEID=@PayrollTypeID))
|
|||
|
set @ProfileRequest=(select count(purid) from ProfileUpdateRequest pr,employee e
|
|||
|
where month(pr.Requestdate)=month(getdate()) AND year(pr.Requestdate)=year(getdate())
|
|||
|
and e.employeeid=pr.RequestEmpID and e.PAYROLLTYPEID=@PayrollTypeID
|
|||
|
)
|
|||
|
set @Sql=@Sql+'LiveEmployee INT,NewJoiner INT,LeftEmployee INT,PostingMissing INT,ConfirmationWaiting int,NextSalaryDate date,ProfileComplitionPercent int';
|
|||
|
set @InsertSql=@InsertSql+cast(@LiveEmployee as varchar) +','+cast(@NewJoiner as varchar) +','+cast(@LeftEmployee as varchar) +','+cast(@PostingMissing as varchar) +','+cast(@ConfirmationWaiting as varchar) +','''+cast(@NextSalaryDate as varchar) +''','+cast(@ProfileComplitionPercent as varchar) ;
|
|||
|
end
|
|||
|
if @ModLeave=1
|
|||
|
begin
|
|||
|
set @LeaveinNextweek=(select count(le.tranid)
|
|||
|
from leaveentry le ,employee e
|
|||
|
where e.employeeid=le.empid
|
|||
|
AND le.aprfromdate>=@WeekStart and le.aprtodate<=@WeekEnd
|
|||
|
AND e.payrolltypeid=@Payrolltypeid
|
|||
|
)
|
|||
|
set @PendingApproval=(select count(wn.employeeid)
|
|||
|
from WFMovementNext wn,employee e
|
|||
|
where e.employeeid=wn.employeeid
|
|||
|
AND month(receivedatetime)=month(getdate()) AND year(receivedatetime)=year(getdate())
|
|||
|
AND e.payrolltypeid=@Payrolltypeid)
|
|||
|
set @LongPending=(select count(wn.employeeid)
|
|||
|
from WFMovementNext wn,employee e
|
|||
|
where e.employeeid=wn.employeeid
|
|||
|
AND dbo.fun_datediff_in_months(receivedatetime, getdate())>=1 --- one month window
|
|||
|
AND e.payrolltypeid=@Payrolltypeid)
|
|||
|
if len(@Sql)>0
|
|||
|
begin
|
|||
|
set @Sql=@Sql+',';
|
|||
|
end
|
|||
|
if len(@InsertSql)>0
|
|||
|
begin
|
|||
|
set @InsertSql=@InsertSql+',';
|
|||
|
end
|
|||
|
set @Sql=@Sql+'LeaveinNextweek int,PendingApproval int,LongPending int';
|
|||
|
set @InsertSql=@InsertSql+cast(@LeaveinNextweek as varchar) +','+cast(@PendingApproval as varchar) +','+cast(@LongPending as varchar)
|
|||
|
end
|
|||
|
if @ModAttendance=1
|
|||
|
begin
|
|||
|
set @RosterMissing=(SELECT count(EMPLOYEEID )
|
|||
|
FROM employee e
|
|||
|
WHERE NOT EXISTS
|
|||
|
(select ws.EMPLOYEEID from employeeworkplansetup ws,monthlyworkplan wp
|
|||
|
where ws.WORKPLANGROUPID=wp.WorkPlanGroupID
|
|||
|
and CONVERT(VARCHAR,wp.WorkDate,106)=CONVERT(VARCHAR,GETDATE(),106)
|
|||
|
AND ws.EMPLOYEEID = e.EMPLOYEEID)
|
|||
|
and status=1
|
|||
|
and PAYROLLTYPEID=@Payrolltypeid)
|
|||
|
set @PresentDays=(select count(e.employeeid) from DAILYATTNPROCESS dp,EMPLOYEE e
|
|||
|
where CONVERT(VARCHAR,attndate,106)=CONVERT(VARCHAR,GETDATE(),106)
|
|||
|
--and AttenType=1 // AttenType not found
|
|||
|
and e.EMPLOYEEID=dp.EMPLOYEEID
|
|||
|
and e.PAYROLLTYPEID=@Payrolltypeid)
|
|||
|
set @AbsentDays=(select count(e.employeeid) from DAILYATTNPROCESS dp,EMPLOYEE e
|
|||
|
where CONVERT(VARCHAR,attndate,106)=CONVERT(VARCHAR,GETDATE(),106)
|
|||
|
--and AttenType=2 // AttenType not found
|
|||
|
and e.EMPLOYEEID=dp.EMPLOYEEID
|
|||
|
and e.PAYROLLTYPEID=@Payrolltypeid)
|
|||
|
|
|||
|
if len(@Sql)>0
|
|||
|
begin
|
|||
|
set @Sql=@Sql+',';
|
|||
|
end
|
|||
|
if len(@InsertSql)>0
|
|||
|
begin
|
|||
|
set @InsertSql=@InsertSql+',';
|
|||
|
end
|
|||
|
set @Sql=@Sql+'RosterMissing int,PresentDays int,AbsentDays int';
|
|||
|
set @InsertSql=@InsertSql+cast(@RosterMissing as varchar) +','+cast(@PresentDays as varchar) +','+cast(@AbsentDays as varchar)
|
|||
|
end
|
|||
|
set @TableName='DashboardInformation';
|
|||
|
exec('drop table '+ @TableName)
|
|||
|
--WAITFOR DELAY '00:00:02'
|
|||
|
set @Sql='CREATE TABLE '+ @TableName+'('+@Sql+')';
|
|||
|
exec sp_executeSQL @Sql
|
|||
|
--WAITFOR DELAY '00:00:02'
|
|||
|
set @InsertSql='Insert into '+@TableName+' values('+@InsertSql+')';
|
|||
|
exec sp_executeSQL @InsertSql
|
|||
|
select * from DashboardInformation
|
|||
|
end
|
|||
|
|
|||
|
|
|||
|
|
|||
|
-- exec sp_DashboardInformation 1,1,1,1
|
|||
|
|
|||
|
|
|||
|
-- select joiningdate from EMPLOYEE
|
|||
|
|
|||
|
|
|||
|
-- select * from ProfileUpdateRequest
|
|||
|
|
|||
|
|
|||
|
--- drop table DashboardInformation
|
|||
|
|
|||
|
------- select * from DashboardInformation
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|
|||
|
-- select * from WFMovementNext
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"CREATE PROCEDURE sp_delete_LeaveEntry_with_Workflow
|
|||
|
@TranID INT
|
|||
|
AS
|
|||
|
--BEGIN
|
|||
|
-- Column name or number of supplied values does not match table definition.
|
|||
|
-- delete process of WFMOVEMENTTASK
|
|||
|
--IF OBJECT_ID ('dbo.DELETED_WFMOVEMENTTASK') IS NULL
|
|||
|
-- BEGIN
|
|||
|
-- SELECT * INTO DELETED_WFMOVEMENTTASK FROM WFMOVEMENTTASK
|
|||
|
-- WHERE WFMOVEMENTTRANID IN (SELECT WFMOVEMENTTRANID FROM WFMOVEMENTTRAN WHERE OBJECTID = @TranID)
|
|||
|
-- END
|
|||
|
--ELSE
|
|||
|
-- BEGIN
|
|||
|
-- INSERT INTO DELETED_WFMOVEMENTTASK
|
|||
|
-- SELECT * FROM WFMOVEMENTTASK
|
|||
|
-- WHERE WFMOVEMENTTRANID IN (SELECT WFMOVEMENTTRANID FROM WFMOVEMENTTRAN WHERE OBJECTID = @TranID)
|
|||
|
-- END
|
|||
|
|
|||
|
--DELETE FROM WFMOVEMENTTASK
|
|||
|
--WHERE WFMOVEMENTTRANID IN (SELECT WFMOVEMENTTRANID FROM WFMOVEMENTTRAN WHERE OBJECTID = @TranID)
|
|||
|
|
|||
|
---- delete process of WFMOVEMENTNEXT
|
|||
|
--IF OBJECT_ID ('dbo.DELETED_WFMOVEMENTNEXT') IS NULL
|
|||
|
-- BEGIN
|
|||
|
-- SELECT * INTO DELETED_WFMOVEMENTNEXT FROM WFMOVEMENTNEXT
|
|||
|
-- WHERE WFMOVEMENTTRANID IN (SELECT WFMOVEMENTTRANID FROM WFMOVEMENTTRAN WHERE OBJECTID = @TranID)
|
|||
|
-- END
|
|||
|
--ELSE
|
|||
|
-- BEGIN
|
|||
|
-- INSERT INTO DELETED_WFMOVEMENTNEXT
|
|||
|
-- SELECT * FROM WFMOVEMENTNEXT
|
|||
|
-- WHERE WFMOVEMENTTRANID IN (SELECT WFMOVEMENTTRANID FROM WFMOVEMENTTRAN WHERE OBJECTID = @TranID)
|
|||
|
-- END
|
|||
|
|
|||
|
-- DELETE FROM WFMOVEMENTNEXT
|
|||
|
--WHERE WFMOVEMENTTRANID IN (SELECT WFMOVEMENTTRANID FROM WFMOVEMENTTRAN WHERE OBJECTID = @TranID)
|
|||
|
|
|||
|
---- delete process of WFMOVEMENTTRAN
|
|||
|
--IF OBJECT_ID ('dbo.DELETED_WFMOVEMENTTRAN') IS NULL
|
|||
|
-- BEGIN
|
|||
|
-- SELECT * INTO DELETED_WFMOVEMENTTRAN FROM WFMOVEMENTTRAN WHERE OBJECTID = @TranID
|
|||
|
-- END
|
|||
|
--ELSE
|
|||
|
-- BEGIN
|
|||
|
-- INSERT INTO DELETED_WFMOVEMENTTRAN
|
|||
|
-- SELECT * FROM WFMOVEMENTTRAN WHERE OBJECTID = @TranID
|
|||
|
-- END
|
|||
|
|
|||
|
--DELETE FROM WFMOVEMENTTRAN WHERE OBJECTID = @TranID
|
|||
|
|
|||
|
---- delete process of LEAVEENTRY
|
|||
|
-- IF OBJECT_ID ('dbo.DELETED_LEAVEENTRY') IS NULL
|
|||
|
-- BEGIN
|
|||
|
-- SELECT * INTO DELETED_LEAVEENTRY FROM LEAVEENTRY WHERE TRANID = @TranID
|
|||
|
-- END
|
|||
|
--ELSE
|
|||
|
-- BEGIN
|
|||
|
-- INSERT INTO DELETED_LEAVEENTRY
|
|||
|
-- SELECT * FROM LEAVEENTRY WHERE TRANID = @TranID
|
|||
|
-- END
|
|||
|
|
|||
|
--DELETE FROM LEAVEENTRY WHERE TRANID = @TranID
|
|||
|
--END
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"CREATE PROCEDURE [dbo].[sp_Insert_DailyAttendanceAllowance]
|
|||
|
@DailyAttendanceProcessID INT,
|
|||
|
@AttnDate DATETIME,
|
|||
|
@EmployeeID INT,
|
|||
|
@ShiftID INT,
|
|||
|
@PayrollTypeID INT,
|
|||
|
@OtherBenifitItemID INT,
|
|||
|
@OtherBenifitValue money,
|
|||
|
@SalaryMonth INT,
|
|||
|
@IsArrear INT,
|
|||
|
@AutoCreated INT,
|
|||
|
@ManualEdited INT,
|
|||
|
|
|||
|
@CreatedBy INT,
|
|||
|
@CreatedDate DATETIME,
|
|||
|
@ModifiedBy INT,
|
|||
|
@ModifiedDate DATETIME
|
|||
|
AS
|
|||
|
BEGIN
|
|||
|
|
|||
|
SET NOCOUNT ON;
|
|||
|
|
|||
|
|
|||
|
DECLARE @DailyAttendanceAllowanceCount INT=0;
|
|||
|
SET @DailyAttendanceAllowanceCount = (Select COUNT(*)
|
|||
|
FROM DailyAttendanceAllowance WHERE EmployeeID=@EmployeeID AND AttnDate=@AttnDate);
|
|||
|
|
|||
|
IF @DailyAttendanceAllowanceCount > 0
|
|||
|
BEGIN
|
|||
|
-- Update Script
|
|||
|
UPDATE DailyAttendanceAllowance
|
|||
|
SET
|
|||
|
ShiftID = @ShiftID,
|
|||
|
ModifiedBy = @ModifiedBy, ModifiedDate = @ModifiedDate,
|
|||
|
PayrollTypeID = @PayrollTypeID , OtherBenifitItemID =@OtherBenifitItemID, OtherBenifitValue = @OtherBenifitValue,
|
|||
|
SalaryMonth = @SalaryMonth, IsArrear = @IsArrear , AutoCreated = @AutoCreated , ManualEdited = @ManualEdited
|
|||
|
WHERE EmployeeID=@EmployeeID AND AttnDate=@AttnDate
|
|||
|
END
|
|||
|
ELSE
|
|||
|
BEGIN
|
|||
|
-- Insert Script
|
|||
|
INSERT INTO DailyAttendanceAllowance(
|
|||
|
DailyAttendanceProcessID, AttnDate, EmployeeID, ShiftID, PayrollTypeID, CreatedBy, CreatedDate,
|
|||
|
OtherBenifitItemID, OtherBenifitValue, SalaryMonth, IsArrear,AutoCreated,ManualEdited
|
|||
|
)
|
|||
|
VALUES(
|
|||
|
null, @AttnDate, @EmployeeID, @ShiftID, @PayrollTypeID, @CreatedBy, @CreatedDate,
|
|||
|
@OtherBenifitItemID, @OtherBenifitValue, @SalaryMonth, @IsArrear, @AutoCreated,@ManualEdited
|
|||
|
)
|
|||
|
END
|
|||
|
END
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"CREATE PROCEDURE [dbo].[sp_Insert_DailyAttnProcess]
|
|||
|
@EMPLOYEEID INT,
|
|||
|
@AttnDate DATETIME,
|
|||
|
@ShiftID INT ,
|
|||
|
@WorkDayType SMALLINT ,
|
|||
|
@AttenType SMALLINT ,
|
|||
|
@Comments VARCHAR (250) ,
|
|||
|
@Reason VARCHAR (250) ,
|
|||
|
@IsManualEntry BIT ,
|
|||
|
@IsLate BIT ,
|
|||
|
@LateHour DECIMAL (28,16) ,
|
|||
|
@EarlyHour DECIMAL (28,16) ,
|
|||
|
@OTHour DECIMAL (28,16) ,
|
|||
|
@CREATEDBY INT ,
|
|||
|
@CREATEDDATE DATETIME ,
|
|||
|
@OtRemarks VARCHAR (150) ,
|
|||
|
@WFStatus INT ,
|
|||
|
@ApprovedOTHOUR DECIMAL (6,2) ,
|
|||
|
@LMRemarks VARCHAR (400) ,
|
|||
|
@IsFromMobile BIT ,
|
|||
|
@ReferenceID INT ,
|
|||
|
@actualShiftID INT ,
|
|||
|
@Empremarks VARCHAR (200) ,
|
|||
|
@LineManagerID INT ,
|
|||
|
@OnbehalfEmpID INT ,
|
|||
|
@WorkHour MONEY ,
|
|||
|
@InTimeNearestAddress VARCHAR (500) ,
|
|||
|
@OutTimeNearestAddress VARCHAR (500) ,
|
|||
|
@InTimeLatitude VARCHAR (200) ,
|
|||
|
@OutTimeLatitude VARCHAR (200) ,
|
|||
|
@InTimeLongitude VARCHAR (200) ,
|
|||
|
@outTimeLongitude VARCHAR (200) ,
|
|||
|
@LMApproveDate DATETIME ,
|
|||
|
@EmpApplyDate DATETIME ,
|
|||
|
@InTime DATETIME ,
|
|||
|
@OutTime DATETIME ,
|
|||
|
@ActualInTime DATETIME ,
|
|||
|
@ActualOutTime DATETIME ,
|
|||
|
@MODIFIEDBY INT ,
|
|||
|
@MODIFIEDDATE DATETIME
|
|||
|
|
|||
|
AS
|
|||
|
BEGIN
|
|||
|
|
|||
|
SET NOCOUNT ON;
|
|||
|
|
|||
|
DECLARE @DailyAttnProcessCount INT=0;
|
|||
|
SET @DailyAttnProcessCount=(Select COUNT(*) from DailyAttnProcess WHERE EmployeeID=@EmployeeID AND AttnDate=@AttnDate);
|
|||
|
|
|||
|
IF @DailyAttnProcessCount>0
|
|||
|
BEGIN
|
|||
|
-- Update Script (no attentype found on employee table)
|
|||
|
UPDATE DailyAttnProcess SET ShiftID=@ShiftID, InTime=@InTime, OutTime=@OutTime --,AttenType=@AttenType
|
|||
|
,Comments=@Comments,
|
|||
|
IsManualEntry=@IsManualEntry,IsFromMobile=@IsFromMobile,LateHour=@LateHour, EarlyHour=@EarlyHour, OTHour=@OTHour,
|
|||
|
ReferenceID=@ReferenceID, WorkDayType=@WorkDayType, Reason=@Reason, IsLate=@IsLate, OtRemarks=@OtRemarks,
|
|||
|
WFStatus=@WFStatus,ApprovedOTHOUR=@ApprovedOTHOUR, LMRemarks=@LMRemarks,ActualInTime=@ActualInTime, ActualOutTime=@ActualOutTime,
|
|||
|
actualShiftID=@ActualShiftID, Empremarks=@Empremarks, EmpApplyDate=@EmpApplyDate, LMApproveDate=@LMApproveDate, LineManagerID=@LineManagerID,
|
|||
|
OnbehalfEmpID=@OnbehalfEmpID,WorkHour=@WorkHour,InTimeNearestAddress=@InTimeNearestAddress,OutTimeNearestAddress=@OutTimeNearestAddress,
|
|||
|
InTimeLatitude=@InTimeLatitude,OutTimeLatitude=@OutTimeLatitude,InTimeLongitude =@InTimeLongitude ,outTimeLongitude=@outTimeLongitude,
|
|||
|
ModifiedBy=@ModifiedBy, ModifiedDate=@ModifiedDate
|
|||
|
WHERE EmployeeID=@EmployeeID AND AttnDate=@AttnDate
|
|||
|
END
|
|||
|
|
|||
|
ELSE
|
|||
|
BEGIN
|
|||
|
-- Insert Script
|
|||
|
INSERT INTO DailyAttnProcess(EmployeeID, AttnDate,ShiftID, InTime, OutTime --,AttenType
|
|||
|
,Comments,
|
|||
|
IsManualEntry,IsFromMobile,LateHour, EarlyHour, OTHour,
|
|||
|
ReferenceID, WorkDayType, Reason, IsLate, OtRemarks,
|
|||
|
WFStatus,ApprovedOTHOUR, LMRemarks,ActualInTime, ActualOutTime,
|
|||
|
actualShiftID, Empremarks, EmpApplyDate, LMApproveDate, LineManagerID,
|
|||
|
OnbehalfEmpID,WorkHour,InTimeNearestAddress,OutTimeNearestAddress,
|
|||
|
InTimeLatitude,OutTimeLatitude,InTimeLongitude,outTimeLongitude,
|
|||
|
CREATEDBY, CREATEDDATE)
|
|||
|
VALUES(@EmployeeID, @AttnDate,@ShiftID, @InTime, @OutTime --,@AttenType
|
|||
|
,@Comments,
|
|||
|
@IsManualEntry,@IsFromMobile,@LateHour, @EarlyHour, @OTHour,
|
|||
|
@ReferenceID, @WorkDayType, @Reason, @IsLate, @OtRemarks,
|
|||
|
@WFStatus,@ApprovedOTHOUR, @LMRemarks,@ActualInTime, @ActualOutTime,
|
|||
|
@ActualShiftID, @Empremarks, @EmpApplyDate, @LMApproveDate, @LineManagerID,
|
|||
|
@OnbehalfEmpID,@WorkHour,@InTimeNearestAddress,@OutTimeNearestAddress,
|
|||
|
@InTimeLatitude,@OutTimeLatitude,@InTimeLongitude ,@outTimeLongitude,
|
|||
|
@CREATEDBY, @CREATEDDATE)
|
|||
|
END
|
|||
|
|
|||
|
END
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"create Procedure spShowRelationShips
|
|||
|
(
|
|||
|
@Table varchar(250) = null,
|
|||
|
@RelatedTable varchar(250) = null
|
|||
|
)
|
|||
|
as
|
|||
|
begin
|
|||
|
if @Table is null and @RelatedTable is null
|
|||
|
select object_name(k.constraint_object_id) ForeginKeyName,
|
|||
|
object_name(k.Parent_Object_id) TableName,
|
|||
|
object_name(k.referenced_object_id) RelatedTable,
|
|||
|
c.Name RelatedColumnName,
|
|||
|
object_name(rc.object_id) + '.' + rc.name RelatedKeyField
|
|||
|
from sys.foreign_key_columns k
|
|||
|
left join sys.columns c on object_name(c.object_id) = object_name(k.Parent_Object_id) and c.column_id = k.parent_column_id
|
|||
|
left join sys.columns rc on object_name(rc.object_id) = object_name(k.referenced_object_id) and rc.column_id = k.referenced_column_id
|
|||
|
order by 2,3
|
|||
|
|
|||
|
if @Table is not null and @RelatedTable is null
|
|||
|
select object_name(k.constraint_object_id) ForeginKeyName,
|
|||
|
object_name(k.Parent_Object_id) TableName,
|
|||
|
object_name(k.referenced_object_id) RelatedTable,
|
|||
|
c.Name RelatedColumnName,
|
|||
|
object_name(rc.object_id) + '.' + rc.name RelatedKeyField
|
|||
|
from sys.foreign_key_columns k
|
|||
|
left join sys.columns c on object_name(c.object_id) = object_name(k.Parent_Object_id) and c.column_id = k.parent_column_id
|
|||
|
left join sys.columns rc on object_name(rc.object_id) = object_name(k.referenced_object_id) and rc.column_id = k.referenced_column_id
|
|||
|
where object_name(k.Parent_Object_id) =@Table
|
|||
|
order by 2,3
|
|||
|
|
|||
|
if @Table is null and @RelatedTable is not null
|
|||
|
select object_name(k.constraint_object_id) ForeginKeyName,
|
|||
|
object_name(k.Parent_Object_id) TableName,
|
|||
|
object_name(k.referenced_object_id) RelatedTable,
|
|||
|
c.Name RelatedColumnName,
|
|||
|
object_name(rc.object_id) + '.' + rc.name RelatedKeyField
|
|||
|
from sys.foreign_key_columns k
|
|||
|
left join sys.columns c on object_name(c.object_id) = object_name(k.Parent_Object_id) and c.column_id = k.parent_column_id
|
|||
|
left join sys.columns rc on object_name(rc.object_id) = object_name(k.referenced_object_id) and rc.column_id = k.referenced_column_id
|
|||
|
where object_name(k.referenced_object_id) =@RelatedTable
|
|||
|
order by 2,3
|
|||
|
|
|||
|
|
|||
|
|
|||
|
end
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"create function fun_datediff_in_months
|
|||
|
(
|
|||
|
@StartDate date,
|
|||
|
@EndDate date
|
|||
|
)
|
|||
|
returns int
|
|||
|
as
|
|||
|
begin
|
|||
|
declare @months int=0;
|
|||
|
set @months=( select CAST(DATEDIFF(MONTH, @StartDate, @EndDate) AS int) -
|
|||
|
(DATEPART(dd,@StartDate) - 1) / DATEDIFF(DAY, @StartDate, DATEADD(MONTH, 1, @StartDate)) +
|
|||
|
(DATEPART(dd,@EndDate)*1 ) / DATEDIFF(DAY, @EndDate, DATEADD(MONTH, 1, @EndDate)))
|
|||
|
return @months
|
|||
|
end
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"CREATE FUNCTION GetDeptHeadID(@employeeId as INT)
|
|||
|
RETURNS varchar(15)
|
|||
|
AS
|
|||
|
BEGIN
|
|||
|
DECLARE @EmployeeNo VARCHAR(15);
|
|||
|
BEGIN
|
|||
|
WITH
|
|||
|
cteReports (Organogramid, PositionName ,PARENTID, TIER )
|
|||
|
AS
|
|||
|
(
|
|||
|
SELECT Organogramid, PositionName,PARENTID, organogram.TIER
|
|||
|
FROM organogram ,organEmployee
|
|||
|
WHERE organogram.ORGANOGRAMID =organEmployee.NODEID and organEmployee.EMPLOYEEID =@employeeId
|
|||
|
UNION ALL
|
|||
|
SELECT e.Organogramid, e.PositionName, e.PARENTID, e.TIER
|
|||
|
FROM organogram e
|
|||
|
INNER JOIN cteReports r
|
|||
|
ON e.Organogramid = r.PARENTID
|
|||
|
)
|
|||
|
SELECT @EmployeeNo=
|
|||
|
em.EMPLOYEENO
|
|||
|
FROM cteReports
|
|||
|
left join ORGANPOSITION on cteReports.Organogramid =ORGANPOSITION.nodeid
|
|||
|
left join OGPositionType on OGPositionType.OGPOSITIONTYPEID =ORGANPOSITION.POSITIONTYPEID
|
|||
|
left JOIN organEmployee oe on oe.NODEID = cteReports.Organogramid
|
|||
|
left JOIN employee em on em.EMPLOYEEID = oe.EMPLOYEEID
|
|||
|
WHERE OGPOSITIONTYPE=3 AND tier=2
|
|||
|
order by cteReports.tier DESC
|
|||
|
END
|
|||
|
RETURN @EmployeeNo
|
|||
|
END
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"CREATE FUNCTION [dbo].[GetFormattedDate](@SelectedDate DATETIME, @IsTimeNeeded BIT)
|
|||
|
RETURNS VARCHAR(20)
|
|||
|
AS
|
|||
|
BEGIN
|
|||
|
|
|||
|
DECLARE @formattedDateTime VARCHAR(20);
|
|||
|
|
|||
|
IF @IsTimeNeeded = 1
|
|||
|
Begin
|
|||
|
SET @formattedDateTime = CONVERT(VARCHAR, @SelectedDate, 106) + ' ' +STUFF(RIGHT(CONVERT(VARCHAR,@SelectedDate,100),7),6,0,' ')
|
|||
|
END
|
|||
|
ELSE
|
|||
|
BEGIN
|
|||
|
SET @formattedDateTime = CONVERT(VARCHAR, @SelectedDate, 106)
|
|||
|
END
|
|||
|
|
|||
|
RETURN @formattedDateTime
|
|||
|
END
|
|||
|
GO");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"DROP VIEW Salary
|
|||
|
CREATE VIEW SALARY
|
|||
|
AS
|
|||
|
SELECT EMPLOYEEID,
|
|||
|
SALARYMONTH,
|
|||
|
ITEMGROUP,
|
|||
|
ITEMCODE,
|
|||
|
ITEMID,
|
|||
|
DESCRIPTION,
|
|||
|
CHANGEDAMOUNT,
|
|||
|
CCID,
|
|||
|
PAYROLLTYPEID
|
|||
|
FROM(SELECT emp.EMPLOYEEID,
|
|||
|
FORMAT(b.SalaryMonth, 'DD Mon YYYY') SalaryMonth,
|
|||
|
b.ITEMGROUP,
|
|||
|
b.ITEMCODE,
|
|||
|
b.ITEMID,
|
|||
|
b.DESCRIPTION,
|
|||
|
b.CHANGEDAMOUNT,
|
|||
|
(SELECT c.COSTCENTERID
|
|||
|
FROM SALARYEMPCOSTCENTER c
|
|||
|
WHERE c.EMPLOYEEID = emp.EMPLOYEEID
|
|||
|
AND c.SALARYMONTHLYID = b.SALARYMONTHLYID)
|
|||
|
ccid,
|
|||
|
b.PAYROLLTYPEID
|
|||
|
FROM EMPLOYEE emp
|
|||
|
LEFT OUTER JOIN
|
|||
|
(SELECT sm.EMPLOYEEID,
|
|||
|
sm.SALARYMONTH,
|
|||
|
sm.PAYROLLTYPEID,
|
|||
|
smd.*
|
|||
|
FROM SALARYMONTHLYDETAIL smd, SALARYMONTHLY sm
|
|||
|
WHERE smd.SALARYMONTHLYID = sm.SALARYMONTHLYID) b
|
|||
|
ON(b.EMPLOYEEID = emp.EMPLOYEEID)) tab1
|
|||
|
WHERE salarymonth IS NOT NULL;
|
|||
|
GO");
|
|||
|
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"IF COL_LENGTH('dbo.userrole', 'eventdate') IS NOT NULL
|
|||
|
BEGIN
|
|||
|
update userrole set EVENTDATE ='1 Jan 2023'
|
|||
|
END");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"IF COL_LENGTH('dbo.users', 'usertype') IS NOT NULL
|
|||
|
BEGIN
|
|||
|
update users set usertype =0 WHERE userid in ( -9,-8)
|
|||
|
END");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"IF COL_LENGTH('dbo.PasswordHistory', 'passwordhistoryid') IS NOT NULL
|
|||
|
BEGIN
|
|||
|
IF OBJECT_ID('dbo.[PK_PasswordHistory]') IS NOT NULL
|
|||
|
begin
|
|||
|
ALTER TABLE dbo.PasswordHistory DROP CONSTRAINT PK_PasswordHistory;
|
|||
|
end
|
|||
|
ALTER TABLE PasswordHistory ALTER COLUMN PassHisID int NULL;
|
|||
|
--update PasswordHistory set passwordhistoryid = PassHisID;
|
|||
|
END");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"IF COL_LENGTH('dbo.HOLIDAYCALENDAR', 'EntryDate') IS NOT NULL
|
|||
|
BEGIN
|
|||
|
ALTER TABLE HOLIDAYCALENDAR ALTER COLUMN EntryDate DateTime NULL
|
|||
|
END");
|
|||
|
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat(@"IF COL_LENGTH('dbo.HOLIDAYCALENDAR', 'userid') IS NOT NULL
|
|||
|
BEGIN
|
|||
|
ALTER TABLE HOLIDAYCALENDAR ALTER COLUMN userid DateTime NULL
|
|||
|
END");
|
|||
|
|
|||
|
|
|||
|
#endregion
|
|||
|
|
|||
|
//foreign key
|
|||
|
sql.AppendFormat("\r\n\r\n");
|
|||
|
sql.AppendFormat("-------------- Make columns name upper case ------------------------------------\r\n\r\n");
|
|||
|
DataTable dtCols = GetColumnList(EnumTargetType.Destination);
|
|||
|
|
|||
|
if(dtCols!= null)
|
|||
|
{
|
|||
|
foreach(DataRow dr in dtCols.Rows)
|
|||
|
{
|
|||
|
sql.AppendFormat("\r\n");
|
|||
|
sql.AppendFormat(dr[0].ToString());
|
|||
|
sql.AppendFormat("\r\n");
|
|||
|
sql.AppendFormat("GO");
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
WriteScript(sql.ToString());
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
|
|||
|
catch (Exception ex)
|
|||
|
{
|
|||
|
MessageBox.Show("exception occured while creating table:" + ex.Message + "\t" + ex.GetType(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
private string GetColumnSqlCREATE(TableList row)
|
|||
|
{
|
|||
|
StringBuilder sql = new StringBuilder();
|
|||
|
var identityColumnExist = _dtIdentityColumns.AsEnumerable().Where(x => x[0].ToString().ToLower() == row.TableName.ToLower().ToLower() && x[1].ToString().ToLower() == row.ColumnName.ToLower().ToLower()).Any();
|
|||
|
if (identityColumnExist)
|
|||
|
{
|
|||
|
sql.AppendFormat("\t[{0}] [{1}] {2} IDENTITY(1,1) ",
|
|||
|
row.ColumnName,
|
|||
|
row.DataType,
|
|||
|
(HasLength(row.DataType.ToString())) ? "(" + row.Length.ToString() + ")" : (HasPrecisionAndScale(row.DataType)) ? "(" + row.Precision.ToString() + "," + row.Scale.ToString() + ")" : ""
|
|||
|
);
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
sql.AppendFormat("\t[{0}] [{1}] {2} ",
|
|||
|
row.ColumnName,
|
|||
|
row.DataType,
|
|||
|
(HasLength(row.DataType.ToString())) ? "(" + row.Length.ToString() + ")" : (HasPrecisionAndScale(row.DataType)) ? "(" + row.Precision.ToString() + "," + row.Scale.ToString() + ")" : ""
|
|||
|
);
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
|
|||
|
if (row.IsDefaultValueRequired || !String.IsNullOrEmpty(row.DefaultValue))
|
|||
|
{
|
|||
|
row.DefaultValue = DefaultValueSet(row.DefaultValue, row.ColumnName);
|
|||
|
|
|||
|
if (row.DataType.ToLower() == "int" || row.DataType.ToLower() == "smallint" ||
|
|||
|
row.DataType.ToLower() == "bit" ||
|
|||
|
row.DataType.ToLower() == "money" ||
|
|||
|
row.DataType.ToLower() == "numeric" ||
|
|||
|
row.DataType.ToLower() == "decimal" ||
|
|||
|
row.DataType.ToLower() == "float" ||
|
|||
|
row.DataType.ToLower() == "tinyint" ||
|
|||
|
((row.DataType.ToLower() == "date" || row.DataType.ToLower() == "datetime" || row.DataType.ToLower() == "datetime2") && row.DefaultValue == "GETDATE()"))
|
|||
|
{
|
|||
|
sql.AppendFormat("{0}",
|
|||
|
"DEFAULT (" + row.DefaultValue + ")");
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
if (row.DefaultValue.Contains("'"))
|
|||
|
{
|
|||
|
sql.AppendFormat("{0}",
|
|||
|
"DEFAULT (" + row.DefaultValue + ")");
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
sql.AppendFormat("{0}",
|
|||
|
"DEFAULT ('" + row.DefaultValue + "')");
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
}
|
|||
|
if (row.AllowNull.ToLower() == "yes")
|
|||
|
{
|
|||
|
sql.AppendFormat("{0}",
|
|||
|
"NULL");
|
|||
|
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
sql.AppendFormat("{0}",
|
|||
|
"NOT NULL");
|
|||
|
|
|||
|
}
|
|||
|
sql.AppendFormat(",");
|
|||
|
sql.AppendFormat("\r\n");
|
|||
|
return sql.ToString();
|
|||
|
}
|
|||
|
|
|||
|
private string GetColumnSqlALTER(TableList row)
|
|||
|
{
|
|||
|
StringBuilder sql = new StringBuilder();
|
|||
|
|
|||
|
sql.AppendFormat("\t[{0}] [{1}] {2} {3} ",
|
|||
|
row.ColumnName,
|
|||
|
row.DataType,
|
|||
|
(HasLength(row.DataType.ToString())) ? "(" + row.Length.ToString() + ")" : (HasPrecisionAndScale(row.DataType)) ? "(" + row.Precision.ToString() + "," + row.Scale.ToString() + ")" : "",
|
|||
|
(row.AllowNull.ToLower() == "yes") ? "NULL" : "NOT NULL" //,
|
|||
|
// row.IsDefaultValueRequired ? ((row.DataType.ToLower() == "int" || row.DataType.ToLower() == "smallint" || ((row.DataType.ToLower() == "date" || row.DataType.ToLower() == "datetime" || row.DataType.ToLower() == "datetime2") && row.DefaultValue == "GETDATE()")) ? "DEFAULT (" + row.DefaultValue + ")" : "DEFAULT ('" + row.DefaultValue + "')") : string.Empty
|
|||
|
// row.IsDefaultValueRequired ? ((row.DataType.ToLower() == "int" || row.DataType.ToLower() == "smallint") ? "DEFAULT (" + row.DefaultValue + ")" : "DEFAULT ('" + row.DefaultValue + "')") : string.Empty
|
|||
|
|
|||
|
);
|
|||
|
if (row.IsDefaultValueRequired || !String.IsNullOrEmpty(row.DefaultValue))
|
|||
|
{
|
|||
|
row.DefaultValue = DefaultValueSet(row.DefaultValue, row.ColumnName);
|
|||
|
|
|||
|
if (row.DataType.ToLower() == "int" || row.DataType.ToLower() == "smallint" ||
|
|||
|
row.DataType.ToLower() == "bit" ||
|
|||
|
row.DataType.ToLower() == "money" ||
|
|||
|
row.DataType.ToLower() == "numeric" ||
|
|||
|
row.DataType.ToLower() == "decimal" ||
|
|||
|
row.DataType.ToLower() == "float" ||
|
|||
|
row.DataType.ToLower() == "tinyint" ||
|
|||
|
((row.DataType.ToLower() == "date" || row.DataType.ToLower() == "datetime" || row.DataType.ToLower() == "datetime2") && row.DefaultValue == "GETDATE()"))
|
|||
|
{
|
|||
|
sql.AppendFormat("{0}",
|
|||
|
"DEFAULT (" + row.DefaultValue + ")");
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
if (row.DefaultValue.Contains("'"))
|
|||
|
{
|
|||
|
sql.AppendFormat("{0}",
|
|||
|
"DEFAULT (" + row.DefaultValue + ")");
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
sql.AppendFormat("{0}",
|
|||
|
"DEFAULT ('" + row.DefaultValue + "')");
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
}
|
|||
|
sql.AppendFormat(",");
|
|||
|
sql.AppendFormat("\r\n");
|
|||
|
return sql.ToString();
|
|||
|
}
|
|||
|
|
|||
|
private string DefaultValueSet(string value, string colName)
|
|||
|
{
|
|||
|
value = DefValueBracesCheck(value);
|
|||
|
if (colName.ToLower() == "userid" || colName.ToLower() == "createdby")
|
|||
|
{
|
|||
|
value = !string.IsNullOrEmpty(textBox1.Text) ? textBox1.Text : value;
|
|||
|
}
|
|||
|
else if (colName.ToLower() == "payrolltypeid")
|
|||
|
{
|
|||
|
value = !string.IsNullOrEmpty(textBox2.Text) ? textBox2.Text : value;
|
|||
|
}
|
|||
|
else if (colName.ToLower() == "createddate")
|
|||
|
{
|
|||
|
value = !string.IsNullOrEmpty(textBox3.Text) ? textBox3.Text : value;
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
return value;
|
|||
|
}
|
|||
|
|
|||
|
private string DefValueBracesCheck(string value)
|
|||
|
{
|
|||
|
string first = "(";
|
|||
|
string last = ")";
|
|||
|
char[] bracketChars = { '(', ')' };
|
|||
|
foreach (char bracket in bracketChars)
|
|||
|
{
|
|||
|
value = value.Replace(bracket.ToString(), string.Empty);
|
|||
|
if (value.ToLower() == "getdate")
|
|||
|
{
|
|||
|
value = value + first + last;
|
|||
|
}
|
|||
|
}
|
|||
|
return value;
|
|||
|
}
|
|||
|
|
|||
|
private StringBuilder DefaultValueAppendAlterColumn(TableList row, StringBuilder sql)
|
|||
|
{
|
|||
|
if (row.IsDefaultValueRequired || !String.IsNullOrEmpty(row.DefaultValue))
|
|||
|
{
|
|||
|
row.DefaultValue = DefaultValueSet(row.DefaultValue, row.ColumnName);
|
|||
|
sql.AppendFormat("ALTER TABLE [{0}] ADD CONSTRAINT [{1}] ",
|
|||
|
row.TableName,
|
|||
|
"DF_" + row.TableName + "_" + row.ColumnName);
|
|||
|
|
|||
|
if (row.DataType.ToLower() == "int" || row.DataType.ToLower() == "smallint" ||
|
|||
|
row.DataType.ToLower() == "bit" ||
|
|||
|
row.DataType.ToLower() == "money" ||
|
|||
|
row.DataType.ToLower() == "numeric" ||
|
|||
|
row.DataType.ToLower() == "decimal" ||
|
|||
|
row.DataType.ToLower() == "float" ||
|
|||
|
row.DataType.ToLower() == "tinyint" ||
|
|||
|
((row.DataType.ToLower() == "date" || row.DataType.ToLower() == "datetime" || row.DataType.ToLower() == "datetime2") && row.DefaultValue.ToLower() == "getdate()"))
|
|||
|
{
|
|||
|
|
|||
|
sql.AppendFormat("{0}",
|
|||
|
"DEFAULT (" + row.DefaultValue + ")");
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
if (row.DefaultValue.Contains("'"))
|
|||
|
{
|
|||
|
sql.AppendFormat("{0}",
|
|||
|
"DEFAULT (" + row.DefaultValue + ")");
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
sql.AppendFormat("{0}",
|
|||
|
"DEFAULT ('" + row.DefaultValue + "')");
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
sql.AppendFormat(" FOR {0}",
|
|||
|
row.ColumnName);
|
|||
|
sql.AppendFormat(";\r\n");
|
|||
|
|
|||
|
}
|
|||
|
return sql;
|
|||
|
}
|
|||
|
|
|||
|
private StringBuilder ForeignKeyCreate(DataTable dtFKSource, StringBuilder sql, DataTable dtFKDestination)
|
|||
|
{
|
|||
|
List<string> _oTableNames = _oTableLists.Select(y => y.TableName).Distinct().ToList();
|
|||
|
foreach (var item in _oTableNames)
|
|||
|
{
|
|||
|
string fkCol = null;
|
|||
|
string fkRefCol = null;
|
|||
|
string fkRefTable = null;
|
|||
|
string fkConstraint = null;
|
|||
|
foreach (DataRow dr in dtFKSource.Rows)
|
|||
|
{
|
|||
|
if (item == dr[1].ToString())
|
|||
|
{
|
|||
|
fkConstraint = dr[0].ToString();
|
|||
|
fkCol = dr[2].ToString();
|
|||
|
fkRefTable = dr[3].ToString();
|
|||
|
fkRefCol = dr[4].ToString();
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
if (fkCol != null)
|
|||
|
{
|
|||
|
var fkRefTablePKExist = dtFKDestination.AsEnumerable().Where(x => x[3].ToString().ToLower() == fkRefTable.ToLower() && x[4].ToString().ToLower() == fkRefCol.ToLower() && x[1].ToString().ToLower() == item.ToLower() && x[2].ToString().ToLower() == fkCol.ToLower()).Any();
|
|||
|
if (fkRefTablePKExist == false)
|
|||
|
{
|
|||
|
sql.AppendFormat("\r\n");
|
|||
|
sql.AppendFormat("ALTER TABLE [{0}] ADD CONSTRAINT [{1}] FOREIGN KEY ({2}) REFERENCES {3} ({4});",
|
|||
|
item, fkConstraint, fkCol, fkRefTable, fkRefCol);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
return sql;
|
|||
|
}
|
|||
|
|
|||
|
private StringBuilder ExistingDefaultConstraintCheck(DataTable dtDefaultKeyDestination, StringBuilder sql, TableList row)
|
|||
|
{
|
|||
|
//if (row.IsDefaultValueRequired || !String.IsNullOrEmpty(row.DefaultValue))
|
|||
|
//{
|
|||
|
var PrevDFConExist = dtDefaultKeyDestination.AsEnumerable().Where(x => x[0].ToString().ToLower() == row.TableName.ToLower() && x[1].ToString().ToLower() == row.ColumnName.ToLower()).Any();
|
|||
|
if (PrevDFConExist)
|
|||
|
{
|
|||
|
var defRow = dtDefaultKeyDestination.AsEnumerable().Where(x => x[0].ToString().ToLower() == row.TableName.ToLower() && x[1].ToString().ToLower() == row.ColumnName.ToLower()).FirstOrDefault();
|
|||
|
sql.AppendFormat("ALTER TABLE [{0}] DROP CONSTRAINT {1}",
|
|||
|
row.TableName, defRow[2].ToString()
|
|||
|
);
|
|||
|
sql.AppendFormat(";\r\n");
|
|||
|
}
|
|||
|
//}
|
|||
|
|
|||
|
return sql;
|
|||
|
}
|
|||
|
|
|||
|
private static bool HasLength(string dataType)
|
|||
|
{
|
|||
|
Dictionary<string, bool> dataTypes = new Dictionary<string, bool>();
|
|||
|
dataTypes.Add("bigint", false);
|
|||
|
dataTypes.Add("binary", true);
|
|||
|
dataTypes.Add("bit", false);
|
|||
|
dataTypes.Add("char", true);
|
|||
|
dataTypes.Add("date", false);
|
|||
|
dataTypes.Add("datetime", false);
|
|||
|
dataTypes.Add("datetime2", false);
|
|||
|
dataTypes.Add("datetimeoffset", false);
|
|||
|
dataTypes.Add("decimal", false);
|
|||
|
dataTypes.Add("float", true);
|
|||
|
dataTypes.Add("geography", false);
|
|||
|
dataTypes.Add("geometry", false);
|
|||
|
dataTypes.Add("hierarchyid", false);
|
|||
|
dataTypes.Add("image", false);
|
|||
|
dataTypes.Add("int", false);
|
|||
|
dataTypes.Add("money", false);
|
|||
|
dataTypes.Add("nchar", true);
|
|||
|
dataTypes.Add("ntext", false);
|
|||
|
dataTypes.Add("numeric", false);
|
|||
|
dataTypes.Add("nvarchar", true);
|
|||
|
dataTypes.Add("real", false);
|
|||
|
dataTypes.Add("smalldatetime", false);
|
|||
|
dataTypes.Add("smallint", false);
|
|||
|
dataTypes.Add("smallmoney", false);
|
|||
|
dataTypes.Add("sql_variant", false);
|
|||
|
dataTypes.Add("sysname", false);
|
|||
|
dataTypes.Add("text", false);
|
|||
|
dataTypes.Add("time", false);
|
|||
|
dataTypes.Add("timestamp", false);
|
|||
|
dataTypes.Add("tinyint", false);
|
|||
|
dataTypes.Add("uniqueidentifier", false);
|
|||
|
dataTypes.Add("varbinary", true);
|
|||
|
dataTypes.Add("varchar", true);
|
|||
|
dataTypes.Add("xml", false);
|
|||
|
if (dataTypes.ContainsKey(dataType.ToLower()))
|
|||
|
return dataTypes[dataType.ToLower()];
|
|||
|
return false;
|
|||
|
}
|
|||
|
|
|||
|
private static bool HasPrecisionAndScale(string dataType)
|
|||
|
{
|
|||
|
|
|||
|
if (_dataTypes.ContainsKey(dataType.ToLower()))
|
|||
|
return _dataTypes[dataType.ToLower()];
|
|||
|
return false;
|
|||
|
}
|
|||
|
|
|||
|
private void WriteScript(string script)
|
|||
|
{
|
|||
|
try
|
|||
|
{
|
|||
|
SaveFileDialog sDialog = new SaveFileDialog();
|
|||
|
sDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
|
|||
|
sDialog.FileName = "Comparison Script For " + cmbDestinationDatabase.Text;
|
|||
|
if (sDialog.ShowDialog() == DialogResult.OK)
|
|||
|
{
|
|||
|
File.WriteAllText(sDialog.FileName, script);
|
|||
|
MessageBox.Show("File created at " + sDialog.FileName, "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
|||
|
}
|
|||
|
//var finalPath = string.Empty;
|
|||
|
//var basePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
|
|||
|
////var path = $@"{basePath}Documents\";
|
|||
|
//var path = basePath;
|
|||
|
//Directory.CreateDirectory(path);
|
|||
|
|
|||
|
//finalPath = Path.Combine(path, "Script.txt");
|
|||
|
|
|||
|
//if (File.Exists(finalPath))
|
|||
|
//{
|
|||
|
// File.Delete(finalPath);
|
|||
|
//}
|
|||
|
|
|||
|
//using (var w = new StreamWriter(finalPath))
|
|||
|
//{
|
|||
|
// w.WriteLine("---------------Script File Created-----------------");
|
|||
|
//}
|
|||
|
//using (var w = File.AppendText(finalPath))
|
|||
|
//{
|
|||
|
// if (!string.IsNullOrEmpty(script))
|
|||
|
// w.WriteLine("\n" + script);
|
|||
|
//}
|
|||
|
//MessageBox.Show("Scriot has created for selected tables");
|
|||
|
}
|
|||
|
catch (Exception)
|
|||
|
{
|
|||
|
//ignored
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
public class TableList
|
|||
|
{
|
|||
|
public string TableName { get; set; }
|
|||
|
public string ColumnName { get; set; }
|
|||
|
public string DataType { get; set; }
|
|||
|
public string Length { get; set; }
|
|||
|
public string AllowNull { get; set; }
|
|||
|
public string DefaultValue { get; set; }
|
|||
|
public EnumScriptType ScriptType { get; set; }
|
|||
|
public bool IsDefaultValueRequired { get; set; }
|
|||
|
public string Precision { get; set; }
|
|||
|
public string Scale { get; set; }
|
|||
|
|
|||
|
}
|
|||
|
private void grdList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
|
|||
|
{
|
|||
|
//_oTableLists = new List<TableList>();
|
|||
|
//foreach (DataGridViewRow grd in grdList.Rows)
|
|||
|
//{
|
|||
|
// TableList item = (TableList)grd.Tag;
|
|||
|
// item.DefaultValue = grd.Cells[e.RowIndex].Value.ToString();
|
|||
|
// _oTableLists.Add(item);
|
|||
|
//}
|
|||
|
}
|
|||
|
|
|||
|
private void label13_Click(object sender, EventArgs e)
|
|||
|
{
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
private void Form1_Load(object sender, EventArgs e)
|
|||
|
{
|
|||
|
CreateDataTypePrecision();
|
|||
|
this.Text= "Compare Database --> Version : "+ Assembly.LoadFile(Application.StartupPath + "\\DatabaseComparison.exe").GetName().Version.ToString();
|
|||
|
}
|
|||
|
private void CreateDataTypePrecision()
|
|||
|
{
|
|||
|
_dataTypes.Add("bigint", false);
|
|||
|
_dataTypes.Add("binary", false);
|
|||
|
_dataTypes.Add("bit", false);
|
|||
|
_dataTypes.Add("char", false);
|
|||
|
_dataTypes.Add("date", false);
|
|||
|
_dataTypes.Add("datetime", false);
|
|||
|
_dataTypes.Add("datetime2", false);
|
|||
|
_dataTypes.Add("datetimeoffset", false);
|
|||
|
_dataTypes.Add("decimal", true);
|
|||
|
_dataTypes.Add("float", false);
|
|||
|
_dataTypes.Add("geography", false);
|
|||
|
_dataTypes.Add("geometry", false);
|
|||
|
_dataTypes.Add("hierarchyid", false);
|
|||
|
_dataTypes.Add("image", false);
|
|||
|
_dataTypes.Add("int", false);
|
|||
|
_dataTypes.Add("money", false);
|
|||
|
_dataTypes.Add("nchar", false);
|
|||
|
_dataTypes.Add("ntext", false);
|
|||
|
_dataTypes.Add("numeric", true);
|
|||
|
_dataTypes.Add("nvarchar", false);
|
|||
|
_dataTypes.Add("real", true);
|
|||
|
_dataTypes.Add("smalldatetime", false);
|
|||
|
_dataTypes.Add("smallint", false);
|
|||
|
_dataTypes.Add("smallmoney", false);
|
|||
|
_dataTypes.Add("sql_variant", false);
|
|||
|
_dataTypes.Add("sysname", false);
|
|||
|
_dataTypes.Add("text", false);
|
|||
|
_dataTypes.Add("time", false);
|
|||
|
_dataTypes.Add("timestamp", false);
|
|||
|
_dataTypes.Add("tinyint", false);
|
|||
|
_dataTypes.Add("uniqueidentifier", false);
|
|||
|
_dataTypes.Add("varbinary", false);
|
|||
|
_dataTypes.Add("varchar", false);
|
|||
|
_dataTypes.Add("xml", false);
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
|