纽威
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

2366 lines
98 KiB

using ICSSoft.Entity;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using ICSSoft.Entity;
namespace ICSSoft.Common
{
public class DBHelper
{
private static log4net.ILog log = log4net.LogManager.GetLogger("U8Helper");
private static string connString = System.Configuration.ConfigurationManager.AppSettings["ConnStr"];
private static string ERPConnString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];
private static string ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"];
//// 访问数据库所需要的适配器
//public static string connString = AppConfig.StrConnection;
///// <summary>
///// 根据查询语句获取一个DataTable,对异常捕获无指定要求
///// </summary>
///// <param name="select">查询语句</param>
///// <returns>所查询数据</returns>
//public static DataTable GetDataTable(string select)
//{
// using (SqlConnection m_cnn = new SqlConnection(connString))
// {
// DataTable dt = new DataTable();
// SqlDataAdapter m_da = new SqlDataAdapter(select, m_cnn);
// m_da.SelectCommand.CommandTimeout = 600;
// m_da.SelectCommand.CommandType = CommandType.Text;
// m_da.SelectCommand.CommandText = select;
// m_da.Fill(dt);
// return dt;
// }
//}
/// <summary>
/// 事物取DataTable
/// </summary>
/// <param name="SQl"></param>
/// <param name="cmd"></param>
/// <returns></returns>
public static DataTable SQlReturnData(string SQl, SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlDataAdapter dr = new System.Data.SqlClient.SqlDataAdapter();
cmd.CommandText = SQl;
dr.SelectCommand = cmd;
dr.Fill(dt);
return dt;
}
/// <summary>
/// 依靠数据库连接字符串connectionString,
/// 使用所提供参数,执行返回首行首列命令
/// </summary>
/// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>
/// <param name="commandText">存储过程名称或者T-SQL命令行</param>
/// <returns>返回一个对象,使用Convert.To{Type}将该对象转换成想要的数据类型。</returns>
public static object ExecuteScalar(CommandType cmdType, string cmdText, string conn)
{
try
{
DbCommand cmd = CreateDbCommand();
using (DbConnection connection = CreateDbConnection(conn))
{
PrepareCommand(cmd, connection, null, cmdType, cmdText, null);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
}
catch (Exception ex)
{
//log.Error(ex.Message);
throw;
}
}
/// <summary>
/// 为即将执行准备一个命令
/// </summary>
/// <param name="cmd">SqlCommand对象</param>
/// <param name="conn">SqlConnection对象</param>
/// <param name="isOpenTrans">DbTransaction对象</param>
/// <param name="cmdType">执行命令的类型(存储过程或T-SQL,等等)</param>
/// <param name="cmdText">存储过程名称或者T-SQL命令行, e.g. Select * from Products</param>
/// <param name="cmdParms">SqlParameters to use in the command</param>
private static void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction isOpenTrans, CommandType cmdType, string cmdText, DbParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (isOpenTrans != null)
cmd.Transaction = isOpenTrans;
cmd.CommandType = cmdType;
if (cmdParms != null)
{
cmd.Parameters.AddRange(cmdParms);
}
}
/// <summary>
/// 数据库类型
/// </summary>
public static DatabaseType DbType { get; set; }
/// <summary>
/// 根据配置文件中所配置的数据库类型和传入的
/// 数据库链接字符串来创建相应数据库连接对象
/// </summary>
/// <param name="connectionString"></param>
/// <returns></returns>
public static DbConnection CreateDbConnection(string connectionString)
{
DbConnection conn = null;
switch (DbType)
{
case DatabaseType.SqlServer:
conn = new SqlConnection(connectionString);
break;
//case DatabaseType.Oracle:
// conn = new OracleConnection(connectionString);
// break;
//case DatabaseType.MySql:
// conn = new MySqlConnection(connectionString);
// break;
//case DatabaseType.Access:
// conn = new OleDbConnection(connectionString);
// break;
//case DatabaseType.SQLite:
// conn = new SQLiteConnection(connectionString);
// break;
default:
throw new Exception("数据库类型目前不支持!");
}
return conn;
}
/// <summary>
/// 根据配置文件中所配置的数据库类型
/// 来创建相应数据库命令对象
/// </summary>
/// <returns></returns>
public static DbCommand CreateDbCommand()
{
DbCommand cmd = null;
switch (DbType)
{
case DatabaseType.SqlServer:
cmd = new SqlCommand();
break;
//case DatabaseType.Oracle:
// cmd = new OracleCommand();
// break;
//case DatabaseType.MySql:
// cmd = new MySqlCommand();
// break;
//case DatabaseType.Access:
// cmd = new OleDbCommand();
// break;
//case DatabaseType.SQLite:
// cmd = new SQLiteCommand();
// break;
default:
throw new Exception("数据库类型目前不支持!");
}
return cmd;
}
public enum DatabaseType
{
/// <summary>
/// 数据库类型:Oracle
/// </summary>
Oracle,
/// <summary>
/// 数据库类型:SqlServer
/// </summary>
SqlServer,
/// <summary>
/// 数据库类型:Access
/// </summary>
Access,
/// <summary>
/// 数据库类型:MySql
/// </summary>
MySql,
/// <summary>
/// 数据库类型:SQLite
/// </summary>
SQLite
}
public static bool ExecuteNonQuery(string sql, SqlCommand cmd)
{
try
{
cmd.CommandText = sql;
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
return true;
}
else
{
log.Info("SQL执行受影响行数<0;" + sql);
return false;
}
}
catch (Exception ex)
{
string Params = string.Empty;
foreach (SqlParameter parameter in cmd.Parameters)
{
Params += parameter.SqlValue + "||";
}
log.Error("异常:" + ex.Message + ";\r\n SQL:" + sql + "参数:" + Params);
throw new Exception("程序异常!");
}
}
/// <summary>
/// 获取插入单据的表头表体最大ID
/// </summary>
/// <param name="IDtype"></param>
/// <param name="cAcc_id"></param>
/// <param name="rowCount"></param>
/// <param name="id"></param>
/// <param name="did"></param>
public static void SaveGetrdIDandDID(string IDtype, string cAcc_id, int rowCount, out int id, out int did, SqlCommand cmd)
{
cmd.Parameters.Clear();
try
{
string[] ss = cAcc_id.Split('_');
string ErpCount = ss[1];
string str = @"DECLARE @ID int
DECLARE @DID int
SET @ID = 0
SET @DID = 0
IF NOT EXISTS (SELECT * FROM UFSystem..ua_identity WHERE cacc_id = '{0}' AND cVouchType = '{1}')
BEGIN
INSERT INTO UFSystem..ua_identity(cAcc_Id,cVouchType,iFatherId,iChildId) VALUES('{0}','{1}',1,1)
END
ELSE
BEGIN
UPDATE UFSystem..ua_identity
SET ifatherID = ifatherID +1,ichildID = ichildID + {2}
WHERE cVouchType = '{1}' AND cAcc_id = '{0}'
END
select ifatherID as ID,ichildID as DID FROM UFSystem..ua_identity WHERE cVouchType = '{1}' AND cAcc_id = '{0}' ";
str = string.Format(str, ErpCount, IDtype, rowCount.ToString());
DataTable dt = SQlReturnData(str, cmd);
if (dt.Rows.Count == 0)
{
throw new Exception("ID取得失败");
}
id = Convert.ToInt32(dt.Rows[0]["ID"]);
did = Convert.ToInt32(dt.Rows[0]["DID"]);
#region 测试时屏蔽
// if (IDtype == "rd")
// {
// string sql = @"SELECT CONVERT(BIGINT,SUBSTRING(CONVERT(NVARCHAR(50),MAX(ID)) ,2,LEN(CONVERT(NVARCHAR(50),MAX(ID)))-1)) AS ID ,CONVERT(BIGINT,SUBSTRING(CONVERT(NVARCHAR(50),MAX(DID)) ,2,LEN(CONVERT(NVARCHAR(50),MAX(DID)))-1)) AS DID FROM (
// SELECT MAX(ID) AS ID,MAX(AutoID) AS DID FROM rdrecords01
// UNION
// SELECT MAX(ID) AS ID,MAX(AutoID) AS DID FROM rdrecords08
// UNION
// SELECT MAX(ID) AS ID,MAX(AutoID) AS DID FROM rdrecords09
// UNION
// SELECT MAX(ID) AS ID,MAX(AutoID) AS DID FROM rdrecords10
// UNION
// SELECT MAX(ID) AS ID,MAX(AutoID) AS DID FROM rdrecords11
// UNION
// SELECT MAX(ID) AS ID,MAX(AutoID) AS DID FROM rdrecords32
// ) a";
// DataTable dtCheck = SQlReturnData(sql, cmd);
// if (dtCheck != null && dtCheck.Rows.Count > 0)
// {
// if (id <= Convert.ToInt32(dtCheck.Rows[0]["ID"].ToString()) || did <= Convert.ToInt32(dtCheck.Rows[0]["DID"].ToString()))
// {
// id = Convert.ToInt32(dtCheck.Rows[0]["ID"].ToString()) + 1;
// did = Convert.ToInt32(dtCheck.Rows[0]["DID"].ToString()) + 1;
// sql = string.Format(@" UPDATE UFSystem..ua_identity
// SET ifatherID = {0}, ichildID = {1}
// WHERE cVouchType = '{2}' AND cAcc_id = '{3}' ", id, did, IDtype, ErpCount);
// cmd.CommandText = sql;
// int i = cmd.ExecuteNonQuery();
// }
// }
// }
#endregion
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public static void SaveGetrdIDandDIDs(string IDtype, string cAcc_id, int rowCount, out int id, out int did, SqlCommand cmd)
{
cmd.Parameters.Clear();
try
{
string[] ss = cAcc_id.Split('_');
string ErpCount = ss[1];
string str = @"DECLARE @ID int
DECLARE @DID int
SET @ID = 0
SET @DID = 0
IF NOT EXISTS (SELECT * FROM UFSystem..ua_identity WHERE cacc_id = '{0}' AND cVouchType = '{1}')
BEGIN
INSERT INTO UFSystem..ua_identity(cAcc_Id,cVouchType,iFatherId,iChildId) VALUES('{0}','{1}',1,1)
END
ELSE
BEGIN
UPDATE UFSystem..ua_identity SET ichildID = ichildID + {2}
WHERE cVouchType = '{1}' AND cAcc_id = '{0}'
END
select ifatherID as ID,ichildID as DID FROM UFSystem..ua_identity WHERE cVouchType = '{1}' AND cAcc_id = '{0}' ";
str = string.Format(str, ErpCount, IDtype, rowCount.ToString());
DataTable dt = SQlReturnData(str, cmd);
if (dt.Rows.Count == 0)
{
throw new Exception("ID取得失败");
}
id = Convert.ToInt32(dt.Rows[0]["ID"]);
did = Convert.ToInt32(dt.Rows[0]["DID"]);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 更新主键ID
/// </summary>
/// <param name="IDtype"></param>
/// <param name="cAcc_id"></param>
/// <param name="rowCount"></param>
public static void UpdateIDandDID(string IDtype, string cAcc_id, int rowCount, SqlCommand cmd)
{
try
{
string[] ss = cAcc_id.Split('_');
string ErpCount = ss[1];
string sql = @" UPDATE UFSystem..ua_identity
SET ifatherID = ifatherID +1,ichildID = ichildID + {2}
WHERE cVouchType = '{1}' AND cAcc_id = '{0}' ";
sql = string.Format(sql, ErpCount, IDtype, rowCount.ToString());
cmd.CommandText = sql;
int i = cmd.ExecuteNonQuery();
if (i <= 0)
{
throw new Exception("更新主键ID,DID失败!");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
//public static int ExecuteSql(string sqlUpdate)
//{
// using (SqlConnection conn = new SqlConnection(connString))
// {
// try
// {
// SqlCommand cmd = new SqlCommand();
// cmd.CommandText = sqlUpdate;
// if (conn.State != ConnectionState.Open)
// {
// conn.Open();
// }
// cmd.Connection = conn;
// return cmd.ExecuteNonQuery();
// }
// catch (Exception ex)
// {
// throw new Exception(ex.Message);
// }
// finally
// {
// if (conn.State != ConnectionState.Closed)
// {
// conn.Close();
// }
// }
// }
//}
/// <summary>
/// 执行Insert 或者 Update
/// </summary>
/// <param name="sql"></param>
/// <param name="cmd"></param>
/// <param name="message"></param>
public static void CmdExecuteNonQuery(string sql, SqlCommand cmd, string message)
{
try
{
cmd.CommandText = sql;
int count = cmd.ExecuteNonQuery();
if (count <= 0)
{
string Msg = string.Empty;
foreach (SqlParameter parameter in cmd.Parameters)
{
Msg += "参数名:" + parameter.ParameterName + "参数值:" + parameter.Value;
}
log.Info("受影响行数小于0;" + sql + "\r\n" + Msg);
throw new Exception(message);
}
}
catch (Exception ex)
{
string Msg = string.Empty;
foreach (SqlParameter parameter in cmd.Parameters)
{
Msg += "参数名:" + parameter.ParameterName + "参数值:" + parameter.Value;
}
log.Info("异常:" + ex.Message + "\r\n " + message + "\r\n SQL:" + sql + "\r\n" + Msg);
throw new Exception(message + Environment.NewLine + ex.Message);
}
}
/// <summary>
/// 1 取得单据的默认模板
/// </summary>
/// <param name="ErpName">账套名</param>
/// <param name="CardNumber"></param>
/// <param name="cmd"></param>
/// <returns></returns>
public static string GetDefaultTemplate( string CardNumber, SqlCommand cmd)
{
try
{
string sql = "";
string VouchDEF_ID = string.Empty;
sql = string.Format("SELECT DEF_ID FROM Vouchers WHERE CardNumber = '{0}' ", CardNumber);
cmd.CommandText = sql;
DataTable dtDEF_ID = SQlReturnData(sql, cmd);
if (dtDEF_ID != null && dtDEF_ID.Rows.Count > 0)
{
VouchDEF_ID = dtDEF_ID.Rows[0]["DEF_ID"].ToString();
}
else
{
throw new Exception("获取默认显示模板失败!" + sql);
}
return VouchDEF_ID;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 2 取得单据的表头ID,表体DID
/// </summary>
/// <param name="VouchType">单据类型 如“rd”</param>
/// <param name="ErpName">账套名</param>
/// <param name="RowCount">表体行</param>
/// <returns></returns>
public static VouchKey GetPrimaryKey(string VouchType, string ErpName, int RowCount, SqlCommand cmd)
{
try
{
string num = "1000000000";
int id = 0;
int did = 0;
VouchKey model = new VouchKey();
SaveGetrdIDandDID(VouchType, ErpName, RowCount, out id, out did, cmd);
model.ID = int.Parse(num.Substring(0, 10 - (id.ToString().Length)) + id.ToString());
model.DID = int.Parse(num.Substring(0, 10 - (did.ToString().Length)) + did.ToString());
return model;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public static VouchKey GetPrimaryKeys(string VouchType, string ErpName, int RowCount, SqlCommand cmd)
{
try
{
string num = "1000000000";
int id = 0;
int did = 0;
VouchKey model = new VouchKey();
SaveGetrdIDandDIDs(VouchType, ErpName, RowCount, out id, out did, cmd);
model.DID = int.Parse(num.Substring(0, 10 - (did.ToString().Length)) + did.ToString());
return model;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 3 取得单据编号
/// </summary>
/// <param name="ErpName">账套名</param>
/// <param name="CardNumber"></param>
/// <param name="PreStr">单据前缀</param>
/// <param name="cmd"></param>
/// <returns></returns>
public static int GetVouchCode(string ErpName, string CardNumber, string PreStr, string TableName, SqlCommand cmd)
{
string sql = "";
sql = string.Format("select * from {0}.dbo.VoucherHistory where cSeed = Substring(Convert( varchar(100),GetDate(),112),3,4) and CardNumber = '{1}'", ErpName, CardNumber);
DataTable dt = SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
sql = string.Format(@"UPDATE {0}.dbo.VoucherHistory SET cNumber =cast(( cast(cNumber as int)+1) as nvarchar(30))
WHERE cSeed = SUBSTRING(CONVERT(varchar(100), GETDATE(), 112),3,4) AND CardNumber = '{1}'", ErpName, CardNumber);
CmdExecuteNonQuery(sql, cmd, "更新VoucherHistory表失败!");
}
else
{
sql = string.Format(@"INSERT INTO {0}.dbo.VoucherHistory
SELECT '{1}',NULL,'日期','月',SUBSTRING(CONVERT(varchar(100), GETDATE(), 112),3,4),1,0", ErpName, CardNumber);
CmdExecuteNonQuery(sql, cmd, "插入VoucherHistory表失败!");
}
sql = string.Format(@"DECLARE @Code nvarchar(100)
SELECT @Code = '00000' + CAST(cNumber AS NVARCHAR(50)) FROM {0}.dbo.VoucherHistory
WHERE cSeed = SUBSTRING(CONVERT(varchar(100), GETDATE(), 112),3,4) AND CardNumber = '{1}'
SET @Code = SUBSTRING(CONVERT(varchar(100), GETDATE(), 112),3,4)+RIGHT(@Code,4)
select @Code", ErpName, CardNumber);
int cCode = 0;
cmd.CommandText = sql;
DataTable dtCode = SQlReturnData(sql, cmd);
if (dtCode != null && dtCode.Rows.Count > 0)
{
cCode = int.Parse(dtCode.Rows[0][0].ToString());
}
else
{
throw new Exception("获取单据号失败!");
}
#region
//sql = string.Format("select cCode from " + TableName + " where cCode='{0}'", (PreStr + cCode).ToString());
//cmd.CommandText = sql;
//DataTable dtCodeCheck = SQlReturnData(sql, cmd);
//if (dtCodeCheck != null && dtCodeCheck.Rows.Count > 0)
//{
// throw new Exception("获取单据号重复,保存失败!");
//}
#endregion
return cCode;
}
public static int GetVouchCode(string ErpName, string CardNumber, string TableName, SqlCommand cmd)
{
string sql = "";
sql = string.Format("select * from {0}.dbo.VoucherHistory where CardNumber = '{1}'", ErpName, CardNumber);
DataTable dt = SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
sql = string.Format(@"UPDATE {0}.dbo.VoucherHistory SET cNumber = cNumber+1
WHERE CardNumber = '{1}'", ErpName, CardNumber);
CmdExecuteNonQuery(sql, cmd, "更新VoucherHistory表失败!");
}
else
{
sql = string.Format(@"INSERT INTO {0}.dbo.VoucherHistory
SELECT '{1}',NULL,'单据日期','月',null,1,0", ErpName, CardNumber);
CmdExecuteNonQuery(sql, cmd, "插入VoucherHistory表失败!");
}
sql = string.Format(@"DECLARE @Code nvarchar(100)
SELECT @Code = CAST(cNumber AS NVARCHAR(50)) FROM {0}.dbo.VoucherHistory
WHERE CardNumber = '{1}'
SET @Code = RIGHT(@Code,10)
select @Code", ErpName, CardNumber);
int cCode = 0;
cmd.CommandText = sql;
DataTable dtCode = SQlReturnData(sql, cmd);
if (dtCode != null && dtCode.Rows.Count > 0)
{
cCode = int.Parse(dtCode.Rows[0][0].ToString());
}
else
{
throw new Exception("获取单据号失败!");
}
return cCode;
}
public static string GetPreVouchCode(string ErpName, string CardNumber, string PreStr, SqlCommand cmd)
{
string cCode = "";
string sql = string.Format("SELECT * FROM {0}.dbo.VoucherHistory WHERE CardNumber = '{1}' ", ErpName, CardNumber);
DataTable dt = SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
sql = string.Format(@"UPDATE {0}.dbo.VoucherHistory SET cNumber = CAST((CAST(cNumber AS INT) + 1) AS VARCHAR(30)) WHERE CardNumber = '{1}' ", ErpName, CardNumber);
CmdExecuteNonQuery(sql, cmd, "更新VoucherHistory表失败!");
}
else
{
sql = string.Format(@"INSERT INTO {0}.dbo.VoucherHistory SELECT '{1}', NULL, NULL, NULL, NULL, 1, 0 ", ErpName, CardNumber);
CmdExecuteNonQuery(sql, cmd, "插入VoucherHistory表失败!");
}
sql = string.Format(@"
DECLARE @Code NVARCHAR(100)
SELECT @Code = '0000000' + CAST(cNumber AS NVARCHAR(50)) FROM {0}.dbo.VoucherHistory WHERE CardNumber = '{1}'
SET @Code = '{2}' + RIGHT(@Code, 3)
SELECT @Code ", ErpName, CardNumber, PreStr);
cmd.CommandText = sql;
DataTable dtCode = SQlReturnData(sql, cmd);
if (dtCode != null && dtCode.Rows.Count > 0)
{
cCode = dtCode.Rows[0][0].ToString();
}
else
{
throw new Exception("获取单据号失败!");
}
return cCode;
}
public static string GetRdVouchCode(string ErpName, string CardNumber, SqlCommand cmd)
{
string cCode = "";
string sql = string.Format("SELECT * FROM {0}.dbo.VoucherHistory WHERE CardNumber = '{1}' ", ErpName, CardNumber);
DataTable dt = SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
sql = string.Format(@"UPDATE {0}.dbo.VoucherHistory SET cNumber = CAST((CAST(cNumber AS INT) + 1) AS VARCHAR(30)) WHERE CardNumber = '{1}' ", ErpName, CardNumber);
CmdExecuteNonQuery(sql, cmd, "更新VoucherHistory表失败!");
}
else
{
sql = string.Format(@"INSERT INTO {0}.dbo.VoucherHistory SELECT '{1}', NULL, NULL, NULL, NULL, 1, 0 ", ErpName, CardNumber);
CmdExecuteNonQuery(sql, cmd, "插入VoucherHistory表失败!");
}
sql = string.Format(@"
DECLARE @Code NVARCHAR(100)
SELECT @Code = CAST(cNumber AS NVARCHAR(50)) FROM {0}.dbo.VoucherHistory WHERE CardNumber = '{1}'
SET @Code = @Code
SELECT @Code ", ErpName, CardNumber);
cmd.CommandText = sql;
DataTable dtCode = SQlReturnData(sql, cmd);
if (dtCode != null && dtCode.Rows.Count > 0)
{
cCode = dtCode.Rows[0][0].ToString();
}
else
{
throw new Exception("获取单据号失败!");
}
return cCode;
}
///// <summary>
///// 获取用户的姓名与部门
///// </summary>
///// <param name="cPer_Num">用户编号</param>
///// <param name="cmd"></param>
///// <returns></returns>
//public static UserInfo GetPersonInfo(string cPer_Num, SqlCommand cmd)
//{
// UserInfo person = new UserInfo();
// string sql = @"exec sp_refreshview ua_user ;
// SELECT a.cUser_Id,a.cUser_Name,b.cDepCode FROM ua_user a
// LEFT JOIN dbo.Department b ON a.cDept=b.cDepName
// WHERE cUser_Id ='" + cPer_Num + "'";
// cmd.CommandText = sql;
// DataTable dt = SQlReturnData(sql, cmd);
// if (dt != null && dt.Rows.Count > 0)
// {
// person.DepCode = dt.Rows[0]["cDepCode"].ToString();
// person.UserName = dt.Rows[0]["cUser_Name"].ToString();
// person.UserCode = cPer_Num;
// }
// return person;
//}
/// <summary>
/// 更新现存量
/// </summary>
/// <param name="cmd"></param>
/// <param name="cInvCode"></param>
/// <param name="cWhCode"></param>
/// <param name="cBatch"></param>
public static void UpdateCurrentStock(SqlCommand cmd, string cInvCode, string cWhCode, string cBatch, decimal iQuantity, VouchKey key)
{
#region 1 取得物料的itemID
string sql = @"IF NOT EXISTS(
SELECT Id FROM dbo.SCM_Item WHERE
cinvcode = '{0}')
BEGIN
INSERT INTO dbo.SCM_Item(cInvCode ,cFree1 ,cFree2 ,cFree3 ,cFree4 , cFree5 ,
cFree6 ,cFree7 ,cFree8 ,cFree9 ,cFree10 ,PartId) VALUES('{0}','','','','','','','','','','',0)
END
SELECT Id FROM
dbo.SCM_Item WHERE cinvcode = '{0}'";
sql = string.Format(sql, cInvCode);
cmd.CommandText = sql;
DataTable dtItem = SQlReturnData(sql, cmd);
if (dtItem.Rows.Count == 0)
{
throw new Exception("物料的ItemID取得失败");
}
int ItemID = int.Parse(dtItem.Rows[0]["Id"].ToString());
//log.Info("取得物料的itemID" + sql);
#endregion
#region 2 更新失败,插入现存量
sql = @"SELECT AutoID FROM dbo.CurrentStock
WHERE cWhCode = @cWhCode AND cInvCode = @cInvCode
AND ItemId = @ItemId";
if (cBatch != null)
{
if (bInvBatch(cInvCode, cmd) == true)
sql += " and cBatch='" + cBatch + "' ";
else
sql += " and cBatch='' ";
}
else
{
sql += " and cBatch='' ";
}
cmd.CommandText = sql;
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("@cWhCode", cWhCode));
cmd.Parameters.Add(new SqlParameter("@cInvCode", cInvCode));
cmd.Parameters.Add(new SqlParameter("@ItemId", ItemID));
DataTable dtCurrentStock = SQlReturnData(sql, cmd);
//log.Info("查找现存量:" + sql);
if (dtCurrentStock != null && dtCurrentStock.Rows.Count > 0)
{
sql = @"UPDATE dbo.CurrentStock SET iQuantity = iQuantity + @iQuantity
{0}
WHERE cWhCode = @cWhCode AND cInvCode = @cInvCode
AND ItemId = @ItemId";
if (key.cBustypeUN.Contains("入库") && key.UpdateTodoQuantity == true)
{
sql = string.Format(sql, ",fInQuantity=isnull(fInQuantity,0)-@iQuantity");
}
else if (key.cBustypeUN.Contains("出库") && key.UpdateTodoQuantity == true)
{
sql = string.Format(sql, ",fOutQuantity=isnull(fOutQuantity,0)-@iQuantity");
}
else if (key.cBustypeUN == "调拨" && key.UpdateTodoQuantity == true)
{
sql = string.Format(sql, ", fTransOutQuantity=ISNULL(a.fTransOutQuantity,0)-ISNULL(a.iQuantity,0),fTransInQuantity=ISNULL(fTransInQuantity,0)-ISNULL(a.iQuantity,0)");
}
else
{
sql = string.Format(sql, "");
}
if (cBatch != null)
{
if (bInvBatch(cInvCode, cmd) == true)
sql += " and cBatch='" + cBatch + "' ";
else
sql += " and cBatch='' ";
}
else
{
sql += " and cBatch='' ";
}
cmd.CommandText = sql;
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("@iQuantity", iQuantity));
cmd.Parameters.Add(new SqlParameter("@cWhCode", cWhCode));
cmd.Parameters.Add(new SqlParameter("@cInvCode", cInvCode));
cmd.Parameters.Add(new SqlParameter("@ItemId", ItemID));
CmdExecuteNonQuery(sql, cmd, "更新现存量失败!");
//log.Info("现存量更新:" + sql);
}
else
{
sql = @" INSERT INTO dbo.CurrentStock
(cWhCode,cInvCode,ItemId,cBatch,iSoType,iSodid,iQuantity,
iNum,cFree1,fOutQuantity,fOutNum,fInQuantity,fInNum,cFree2,
cFree3,bStopFlag,fTransInQuantity,fTransInNum,
fTransOutQuantity,fTransOutNum,fPlanQuantity,fPlanNum,fDisableQuantity,
fDisableNum,fAvaQuantity,fAvaNum,BGSPSTOP,fStopQuantity,
fStopNum,ipeqty,ipenum)
SELECT @cWhCode,@cInvCode,@ItemId,@cBatch,'0','',@iQuantity,
'0','','0','0','0','0','',
'','0','0','0','0','0','0','0','0',
'0','0','0','0','0','0','0','0'";
cmd.CommandText = sql;
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("@cWhCode", cWhCode));
cmd.Parameters.Add(new SqlParameter("@cInvCode", cInvCode));
cmd.Parameters.Add(new SqlParameter("@ItemId", ItemID));
cmd.Parameters.Add(new SqlParameter("@iQuantity", iQuantity));
if (cBatch != null)
{
if (bInvBatch(cInvCode, cmd) == true)
cmd.Parameters.Add(new SqlParameter("@cBatch", cBatch));
else
cmd.Parameters.Add(new SqlParameter("@cBatch", ""));
}
else
{
cmd.Parameters.Add(new SqlParameter("@cBatch", ""));
}
CmdExecuteNonQuery(sql, cmd, "插入现存量失败!");
//log.Info("现存量插入:" + sql);
}
#endregion
#region 判断现存量是否足够
//sql = @"IF EXISTS(SELECT AutoID FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0)
// BEGIN
// DECLARE @MSG NVARCHAR(100)
// SELECT @MSG='ERP库存不足!AutoID:'+CAST(AutoID AS NVARCHAR(100)) FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0
// RAISERROR(@MSG,16,1)
// END";
//cmd.CommandText = sql;
//cmd.ExecuteNonQuery();
#endregion
//判断仓库是否记入成本
sql = "SELECT bInCost FROM Warehouse WHERE cWhCode='{0}'";
sql = string.Format(sql, cWhCode);
cmd.CommandText = sql;
DataTable dtwh = SQlReturnData(sql, cmd);
if (!dtwh.Rows[0]["bInCost"].ToString().Equals("0"))
{
#region 3 写入记账表
sql = string.Format(@" INSERT INTO [dbo].[" + key.TableName + @"]
SELECT '{0}','{1}','{2}','{3}'", key.ID, key.DID, key.cVouchTypeUN, key.cBustypeUN);
cmd.CommandText = sql;
CmdExecuteNonQuery(sql, cmd, "采购入库单写入记账表失败!");
#endregion
}
#region 判断现存量是否足够
sql = @"IF EXISTS(SELECT AutoID FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fOutQuantity<0 and cWhCode = '{0}' AND cInvCode = '{1}')
BEGIN
DECLARE @MSG NVARCHAR(100)
SELECT @MSG='ERP待出库数量不足!AutoID:'+CAST(AutoID AS NVARCHAR(100)) FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fOutQuantity<0
RAISERROR(@MSG,16,1)
END";
sql = string.Format(sql,cWhCode,cInvCode);
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
#endregion
}
/// <summary>
/// 更新现存量
/// </summary>
/// <param name="cmd"></param>
/// <param name="cInvCode"></param>
/// <param name="cWhCode"></param>
/// <param name="cBatch"></param>
public static void UpdateCurrentStockNEW(SqlCommand cmd, string cInvCode, string cWhCode, string cBatch, decimal iQuantity, string cFree1, string cFree2, string cFree3, string cFree4, string cFree5, string cFree6, string cFree7, string cFree8, string cFree9, string cFree10, VouchKey key)
{
string newsql = "";
string newsqlvalues = "";
string NewcBatch="";
if (cFree1 != null && cFree1!="")
{
NewcBatch += " and cFree1='{1}' ";
newsql += ",cFree1";
newsqlvalues = ",'" + cFree1 + @"'";
}
if (cFree2 != null && cFree2 != "")
{
NewcBatch += " and cFree2='{2}' ";
newsql += ",cFree2";
newsqlvalues = ",'" + cFree2 + @"'";
}
if (cFree3 != null && cFree3 != "")
{
NewcBatch += " and cFree3='{3}' ";
newsql += ",cFree3";
newsqlvalues = ",'" + cFree3 + @"'";
}
if (cFree4 != null && cFree4 != "")
{
NewcBatch += " and cFree4='{4}' ";
newsql += ",cFree4";
newsqlvalues = ",'" + cFree4 + @"'";
}
if (cFree5 != null && cFree5 != "")
{
NewcBatch += " and cFree5='{5}' ";
newsql += ",cFree5";
newsqlvalues = ",'" + cFree5 + @"'";
}
if (cFree6 != null && cFree6 != "")
{
NewcBatch += " and cFree6='{6}' ";
newsql += ",cFree6";
newsqlvalues = ",'" + cFree6 + @"'";
}
if (cFree7 != null && cFree7 != "")
{
NewcBatch += " and cFree7='{7}' ";
newsql += ",cFree7";
newsqlvalues = ",'" + cFree7 + @"'";
}
if (cFree8 != null && cFree8 != "")
{
NewcBatch += " and cFree8='{8}' ";
newsql += ",cFree8";
newsqlvalues = ",'" + cFree8 + @"'";
}
if (cFree9 != null && cFree9 != "")
{
NewcBatch += " and cFree9='{9}' ";
newsql += ",cFree9";
newsqlvalues = ",'" + cFree9 + @"'";
}
if (cFree10 != null && cFree10 != "")
{
NewcBatch += " and cFree10='{10}' ";
newsql += ",cFree10";
newsqlvalues = ",'" + cFree10 + @"'";
}
#region 1 取得物料的itemID
string sql = @"IF NOT EXISTS(
SELECT Id FROM dbo.SCM_Item WHERE
cinvcode = '{0}' 1=1 )
BEGIN
INSERT INTO dbo.SCM_Item(cInvCode ,cFree1 ,cFree2 ,cFree3 ,cFree4 , cFree5 ,
cFree6 ,cFree7 ,cFree8 ,cFree9 ,cFree10 ,PartId) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}',0)
END
SELECT Id FROM
dbo.SCM_Item WHERE cinvcode = '{0}' 1=1 ";
if (NewcBatch!="")
sql = sql.Replace("1=1",NewcBatch);
else
sql = sql.Replace("1=1", "");
sql = string.Format(sql, cInvCode, cFree1, cFree2, cFree3, cFree4, cFree5, cFree6, cFree7, cFree8, cFree9, cFree10);
cmd.CommandText = sql;
DataTable dtItem = SQlReturnData(sql, cmd);
if (dtItem.Rows.Count == 0)
{
throw new Exception("物料的ItemID取得失败");
}
int ItemID = int.Parse(dtItem.Rows[0]["Id"].ToString());
//log.Info("取得物料的itemID" + sql);
#endregion
#region 2 更新失败,插入现存量
sql = @"SELECT AutoID FROM dbo.CurrentStock
WHERE cWhCode = @cWhCode AND cInvCode = @cInvCode
AND ItemId = @ItemId";
if (cBatch != null)
{
if (bInvBatch(cInvCode, cmd) == true)
sql += " and cBatch='" + cBatch + "' ";
else
sql += " and cBatch='' ";
}
else
sql += " and cBatch='' ";
if (cFree1 != null && cFree1 != "")
sql += " and cFree1='{1}' ";
if (cFree2 != null && cFree2 != "")
sql += " and cFree2='{2}' ";
if (cFree3 != null && cFree3 != "")
sql += " and cFree3='{3}' ";
if (cFree4 != null && cFree4 != "")
sql += " and cFree4='{4}' ";
if (cFree5 != null && cFree5 != "")
sql += " and cFree5='{5}' ";
if (cFree6 != null && cFree6 != "")
sql += " and cFree6='{6}' ";
if (cFree7 != null && cFree7 != "")
sql += " and cFree7='{7}' ";
if (cFree8 != null && cFree8 != "")
sql += " and cFree8='{8}' ";
if (cFree9 != null && cFree9 != "")
sql += " and cFree9='{9}' ";
if (cFree10 != null && cFree10 != "")
sql += " and cFree10='{10}' ";
sql = string.Format(sql, cInvCode, cFree1, cFree2, cFree3, cFree4, cFree5, cFree6, cFree7, cFree8, cFree9, cFree10);
cmd.CommandText = sql;
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("@cWhCode", cWhCode));
cmd.Parameters.Add(new SqlParameter("@cInvCode", cInvCode));
cmd.Parameters.Add(new SqlParameter("@ItemId", ItemID));
DataTable dtCurrentStock = SQlReturnData(sql, cmd);
//log.Info("查找现存量:" + sql);
if (dtCurrentStock != null && dtCurrentStock.Rows.Count > 0)
{
sql = @"UPDATE dbo.CurrentStock SET iQuantity = iQuantity + @iQuantity
{0}
WHERE cWhCode = @cWhCode AND cInvCode = @cInvCode
AND ItemId = @ItemId";
if (key.cBustypeUN.Contains("入库") && key.UpdateTodoQuantity == true)
{
sql = string.Format(sql, ",fInQuantity=isnull(fInQuantity,0)-@iQuantity");
}
else if (key.cBustypeUN.Contains("出库") && key.UpdateTodoQuantity == true)
{
sql = string.Format(sql, ",fOutQuantity=isnull(fOutQuantity,0)-@iQuantity");
}
else if (key.cBustypeUN == "调拨" && key.UpdateTodoQuantity == true)
{
sql = string.Format(sql, ", fTransOutQuantity=ISNULL(a.fTransOutQuantity,0)-ISNULL(a.iQuantity,0),fTransInQuantity=ISNULL(fTransInQuantity,0)-ISNULL(a.iQuantity,0)");
}
else
{
sql = string.Format(sql, "");
}
if (cBatch != null)
{
if (bInvBatch(cInvCode, cmd) == true)
sql += " and cBatch='" + cBatch + "' ";
else
sql += " and cBatch='' ";
}
else
{
sql += " and cBatch='' ";
}
if (cFree1 != null && cFree1 != "")
sql += " and cFree1='{1}' ";
if (cFree2 != null && cFree2 != "")
sql += " and cFree2='{2}' ";
if (cFree3 != null && cFree3 != "")
sql += " and cFree3='{3}' ";
if (cFree4 != null && cFree4 != "")
sql += " and cFree4='{4}' ";
if (cFree5 != null && cFree5 != "")
sql += " and cFree5='{5}' ";
if (cFree6 != null && cFree6 != "")
sql += " and cFree6='{6}' ";
if (cFree7 != null && cFree7 != "")
sql += " and cFree7='{7}' ";
if (cFree8 != null && cFree8 != "")
sql += " and cFree8='{8}' ";
if (cFree9 != null && cFree9 != "")
sql += " and cFree9='{9}' ";
if (cFree10 != null && cFree10 != "")
sql += " and cFree10='{10}' ";
sql = string.Format(sql, cInvCode, cFree1, cFree2, cFree3, cFree4, cFree5, cFree6, cFree7, cFree8, cFree9, cFree10);
cmd.CommandText = sql;
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("@iQuantity", iQuantity));
cmd.Parameters.Add(new SqlParameter("@cWhCode", cWhCode));
cmd.Parameters.Add(new SqlParameter("@cInvCode", cInvCode));
cmd.Parameters.Add(new SqlParameter("@ItemId", ItemID));
CmdExecuteNonQuery(sql, cmd, "更新现存量失败!");
//log.Info("现存量更新:" + sql);
}
else
{
sql = @" INSERT INTO dbo.CurrentStock
(cWhCode,cInvCode,ItemId,cBatch,iSoType,iSodid,iQuantity,
iNum,cFree1,fOutQuantity,fOutNum,fInQuantity,fInNum,
bStopFlag,fTransInQuantity,fTransInNum,
fTransOutQuantity,fTransOutNum,fPlanQuantity,fPlanNum,fDisableQuantity,
fDisableNum,fAvaQuantity,fAvaNum,BGSPSTOP,fStopQuantity,
fStopNum,ipeqty,ipenum,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10)
SELECT @cWhCode,@cInvCode,@ItemId,@cBatch,'0','',@iQuantity,
'0','','0','0','0','0',
'0','0','0','0','0','0','0','0',
'0','0','0','0','0','0','0','0',@cFree1,@cFree2,@cFree3,@cFree4,@cFree5,@cFree6,@cFree7,@cFree8,@cFree9,@cFree10 ";
if (newsql!="")
sql = sql.Replace("1=1", newsql);
else
sql = sql.Replace("1=1", "");
if (newsqlvalues != "")
sql = sql.Replace("2=2", newsqlvalues);
else
sql = sql.Replace("2=2", "");
cmd.CommandText = sql;
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("@cWhCode", cWhCode));
cmd.Parameters.Add(new SqlParameter("@cInvCode", cInvCode));
cmd.Parameters.Add(new SqlParameter("@ItemId", ItemID));
cmd.Parameters.Add(new SqlParameter("@iQuantity", iQuantity));
cmd.Parameters.Add(new SqlParameter("@cFree1", cFree1));
cmd.Parameters.Add(new SqlParameter("@cFree2", cFree2));
cmd.Parameters.Add(new SqlParameter("@cFree3", cFree3));
cmd.Parameters.Add(new SqlParameter("@cFree4", cFree4));
cmd.Parameters.Add(new SqlParameter("@cFree5", cFree5));
cmd.Parameters.Add(new SqlParameter("@cFree6", cFree6));
cmd.Parameters.Add(new SqlParameter("@cFree7", cFree7));
cmd.Parameters.Add(new SqlParameter("@cFree8", cFree8));
cmd.Parameters.Add(new SqlParameter("@cFree9", cFree9));
cmd.Parameters.Add(new SqlParameter("@cFree10", cFree10));
if (cBatch != null)
{
if (bInvBatch(cInvCode, cmd) == true)
cmd.Parameters.Add(new SqlParameter("@cBatch", cBatch));
else
cmd.Parameters.Add(new SqlParameter("@cBatch", ""));
}
else
{
cmd.Parameters.Add(new SqlParameter("@cBatch", ""));
}
CmdExecuteNonQuery(sql, cmd, "插入现存量失败!");
//log.Info("现存量插入:" + sql);
}
#endregion
#region 判断现存量是否足够
//sql = @"IF EXISTS(SELECT AutoID FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0)
// BEGIN
// DECLARE @MSG NVARCHAR(100)
// SELECT @MSG='ERP库存不足!AutoID:'+CAST(AutoID AS NVARCHAR(100)) FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0
// RAISERROR(@MSG,16,1)
// END";
//cmd.CommandText = sql;
//cmd.ExecuteNonQuery();
#endregion
//判断仓库是否记入成本
sql = "SELECT bInCost FROM Warehouse WHERE cWhCode='{0}'";
sql = string.Format(sql, cWhCode);
cmd.CommandText = sql;
DataTable dtwh = SQlReturnData(sql, cmd);
if (!dtwh.Rows[0]["bInCost"].ToString().Equals("0"))
{
#region 3 写入记账表
sql = string.Format(@" INSERT INTO [dbo].[" + key.TableName + @"]
SELECT '{0}','{1}','{2}','{3}'", key.ID, key.DID, key.cVouchTypeUN, key.cBustypeUN);
cmd.CommandText = sql;
CmdExecuteNonQuery(sql, cmd, "采购入库单写入记账表失败!");
#endregion
}
#region 判断现存量是否足够
sql = @"IF EXISTS(SELECT AutoID FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fOutQuantity<0 and cWhCode = '{0}' AND cInvCode = '{1}')
BEGIN
DECLARE @MSG NVARCHAR(100)
SELECT @MSG='ERP待出库数量不足!AutoID:'+CAST(AutoID AS NVARCHAR(100)) FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fOutQuantity<0
RAISERROR(@MSG,16,1)
END";
sql = string.Format(sql, cWhCode, cInvCode);
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
#endregion
}
/// <summary>
/// 判断是否启用批次管理
/// </summary>
/// <param name="cInvCode"></param>
/// <returns></returns>
public static bool bInvBatch(string cInvCode, SqlCommand cmd)
{
try
{
bool flag = false;
string sql = "SELECT bInvBatch FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
DataTable dt = SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
if (Convert.ToBoolean(dt.Rows[0][0]) == true)
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 判断是否启自由项管理
/// </summary>
/// <param name="cInvCode"></param>
/// <returns></returns>
public static bool bFree1(string cInvCode, SqlCommand cmd)
{
try
{
bool flag = false;
string sql = "SELECT bFree1 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
DataTable dt = SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
if (Convert.ToBoolean(dt.Rows[0][0]) == true)
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public static bool bFree2(string cInvCode, SqlCommand cmd)
{
try
{
bool flag = false;
string sql = "SELECT bFree2 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
DataTable dt = SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
if (Convert.ToBoolean(dt.Rows[0][0]) == true)
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public static bool bFree3(string cInvCode, SqlCommand cmd)
{
try
{
bool flag = false;
string sql = "SELECT bFree3 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
DataTable dt = SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
if (Convert.ToBoolean(dt.Rows[0][0]) == true)
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public static bool bFree4(string cInvCode, SqlCommand cmd)
{
try
{
bool flag = false;
string sql = "SELECT bFree4 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
DataTable dt = SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
if (Convert.ToBoolean(dt.Rows[0][0]) == true)
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public static bool bFree5(string cInvCode, SqlCommand cmd)
{
try
{
bool flag = false;
string sql = "SELECT bFree5 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
DataTable dt = SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
if (Convert.ToBoolean(dt.Rows[0][0]) == true)
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public static bool bFree6(string cInvCode, SqlCommand cmd)
{
try
{
bool flag = false;
string sql = "SELECT bFree6 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
DataTable dt = SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
if (Convert.ToBoolean(dt.Rows[0][0]) == true)
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public static bool bFree7(string cInvCode, SqlCommand cmd)
{
try
{
bool flag = false;
string sql = "SELECT bFree7 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
DataTable dt = SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
if (Convert.ToBoolean(dt.Rows[0][0]) == true)
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public static bool bFree8(string cInvCode, SqlCommand cmd)
{
try
{
bool flag = false;
string sql = "SELECT bFree8 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
DataTable dt = SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
if (Convert.ToBoolean(dt.Rows[0][0]) == true)
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public static DataTable bFree(string cInvCode, SqlCommand cmd)
{
try
{
string sql = "SELECT bFree1, bFree2, bFree3, bFree4, bFree5, bFree6, bFree7, bFree8, bFree9, bFree10 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
DataTable dt = SQlReturnData(sql, cmd);
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 判断是否启用保质期管理
/// </summary>
/// <param name="cInvCode"></param>
/// <returns></returns>
public static bool bInvQuality(string cInvCode, SqlCommand cmd)
{
try
{
bool flag = false;
string sql = "SELECT bInvQuality FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
DataTable dt = SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
if (Convert.ToBoolean(dt.Rows[0][0]) == true)
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 判断是否记账
/// </summary>
/// <param name="cInvCode"></param>
/// <returns></returns>
public static bool bInCost(string cWhCode, SqlCommand cmd)
{
try
{
bool flag = false;
string sql = "SELECT bInCost FROM Warehouse WHERE cWhCode ='" + cWhCode + "'";
DataTable dt = SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
if (Convert.ToBoolean(dt.Rows[0][0]) == true)
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// Convert a List{T} to a DataTable.
/// </summary>
public static DataTable ToDataTable<T>(List<T> items)
{
var tb = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
}
foreach (T item in items)
{
var values = new object[props.Length];
for (int i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
tb.Rows.Add(values);
}
return tb;
}
/// <summary>
/// Determine of specified type is nullable
/// </summary>
public static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
/// <summary>
/// Return underlying type if type is Nullable otherwise return the type
/// </summary>
public static Type GetCoreType(Type t)
{
if (t != null && IsNullable(t))
{
if (!t.IsValueType)
{
return t;
}
else
{
return Nullable.GetUnderlyingType(t);
}
}
else
{
return t;
}
}
#region 原
public static DataTable MergeDataTableX(DataTable dt, string AuotID, string cBatch, string iQuantity, string cInvCode, string dMDate, string cFree1, string cFree2, string cFree3, string cFree4, string cFree5, string cFree6, string cFree7, string cFree8, SqlCommand cmd)
{
DataTable dtNew = dt.Clone();
dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[cInvCode], dtNew.Columns[dMDate], dtNew.Columns[cBatch], dtNew.Columns[cFree1], dtNew.Columns[cFree2], dtNew.Columns[cFree3], dtNew.Columns[cFree4], dtNew.Columns[cFree5], dtNew.Columns[cFree6], dtNew.Columns[cFree7], dtNew.Columns[cFree8] };
foreach (DataRow row in dt.Rows)
{
if (string.IsNullOrEmpty(cBatch))
{
cBatch = "";
}
if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
{
row[cBatch] = "";
}
DataRow srow = dtNew.Rows.Find(new object[] { row[cInvCode].ToString(), row[dMDate].ToString(), row[cBatch].ToString(), row[cFree1].ToString(), row[cFree2].ToString(), row[cFree3].ToString(), row[cFree4].ToString(), row[cFree5].ToString(), row[cFree6].ToString(), row[cFree7].ToString(), row[cFree8].ToString() });
if (srow == null)
{
dtNew.Rows.Add(row.ItemArray);
}
else
{
srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
}
}
return dtNew;
}
public static DataTable MergeDataTable(DataTable dt, string AuotID, string cBatch, string iQuantity, string cInvCode, SqlCommand cmd)
{
DataTable dtNew = dt.Clone();
dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[AuotID], dtNew.Columns[cBatch] };
foreach (DataRow row in dt.Rows)
{
if (string.IsNullOrEmpty(cBatch))
{
cBatch = "";
}
if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
{
row[cBatch] = "";
}
DataRow srow = dtNew.Rows.Find(new object[] { row[AuotID].ToString(), row[cBatch].ToString() });
if (srow == null)
{
dtNew.Rows.Add(row.ItemArray);
}
else
{
srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
}
}
return dtNew;
}
public static DataTable MergeDataTableFree(DataTable dt, string AuotID, string cBatch, string iQuantity, string cInvCode, string cFree1, string cFree2, string cFree3, string cFree4, string cFree5, string cFree6, string cFree7, string cFree8, SqlCommand cmd)
{
DataTable dtNew = dt.Clone();
dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[AuotID], dtNew.Columns[cBatch], dtNew.Columns[cFree1], dtNew.Columns[cFree2], dtNew.Columns[cFree3], dtNew.Columns[cFree4], dtNew.Columns[cFree5], dtNew.Columns[cFree6], dtNew.Columns[cFree7], dtNew.Columns[cFree8] };
foreach (DataRow row in dt.Rows)
{
if (string.IsNullOrEmpty(cBatch))
{
cBatch = "";
}
if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
{
row[cBatch] = "";
}
DataRow srow = dtNew.Rows.Find(new object[] { row[AuotID].ToString(), row[cBatch].ToString(), row[cFree1].ToString(), row[cFree2].ToString(), row[cFree3].ToString(), row[cFree4].ToString(), row[cFree5].ToString(), row[cFree6].ToString(), row[cFree7].ToString(), row[cFree8].ToString() });
if (srow == null)
{
dtNew.Rows.Add(row.ItemArray);
}
else
{
srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
}
}
return dtNew;
}
public static DataTable MergeDataTableQC(DataTable dt, string AuotID, string cBatch, string iQuantity, string iNGQuantity, string cInvCode, SqlCommand cmd)
{
DataTable dtNew = dt.Clone();
dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[AuotID], dtNew.Columns[cBatch] };
foreach (DataRow row in dt.Rows)
{
if (string.IsNullOrEmpty(cBatch))
{
cBatch = "";
}
if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
{
row[cBatch] = "";
}
DataRow srow = dtNew.Rows.Find(new object[] { row[AuotID].ToString(), row[cBatch].ToString() });
if (srow == null)
{
dtNew.Rows.Add(row.ItemArray);
}
else
{
srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
srow[iNGQuantity] = decimal.Parse(srow[iNGQuantity].ToString()) + decimal.Parse(row[iNGQuantity].ToString());
}
}
return dtNew;
}
public static DataTable MergeRd08(DataTable dt, string cBatch, string iQuantity, string cInvCode, string dMDate, string cFree1, string cFree2, string cFree3, string cFree4, string cFree5, string cFree6, string cFree7, string cFree8, SqlCommand cmd)
{
DataTable dtNew = dt.Clone();
dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[cInvCode], dtNew.Columns[dMDate], dtNew.Columns[cBatch], dtNew.Columns[cFree1], dtNew.Columns[cFree2], dtNew.Columns[cFree3], dtNew.Columns[cFree4], dtNew.Columns[cFree5], dtNew.Columns[cFree6], dtNew.Columns[cFree7], dtNew.Columns[cFree8] };
foreach (DataRow row in dt.Rows)
{
if (string.IsNullOrEmpty(cBatch))
{
cBatch = "";
}
if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
{
row[cBatch] = "";
}
DataRow srow = dtNew.Rows.Find(new object[] { row[cInvCode].ToString(), row[dMDate].ToString(), row[cBatch].ToString(), row[cFree1].ToString(), row[cFree2].ToString(), row[cFree3].ToString(), row[cFree4].ToString(), row[cFree5].ToString(), row[cFree6].ToString(), row[cFree7].ToString(), row[cFree8].ToString() });
if (srow == null)
{
dtNew.Rows.Add(row.ItemArray);
}
else
{
srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
}
}
return dtNew;
}
public static DataTable MergeRd09(DataTable dt, string cBatch, string iQuantity, string cInvCode, string dMDate, string cFree1, string cFree2, string cFree3, string cFree4, string cFree5, string cFree6, string cFree7, string cFree8, SqlCommand cmd)
{
DataTable dtNew = dt.Clone();
dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[cInvCode], dtNew.Columns[dMDate], dtNew.Columns[cBatch], dtNew.Columns[cFree1], dtNew.Columns[cFree2], dtNew.Columns[cFree3], dtNew.Columns[cFree4], dtNew.Columns[cFree5], dtNew.Columns[cFree6], dtNew.Columns[cFree7], dtNew.Columns[cFree8] };
foreach (DataRow row in dt.Rows)
{
if (string.IsNullOrEmpty(cBatch))
{
cBatch = "";
}
if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
{
row[cBatch] = "";
}
DataRow srow = dtNew.Rows.Find(new object[] { row[cInvCode].ToString(), row[dMDate].ToString(), row[cBatch].ToString(), row[cFree1].ToString(), row[cFree2].ToString(), row[cFree3].ToString(), row[cFree4].ToString(), row[cFree5].ToString(), row[cFree6].ToString(), row[cFree7].ToString(), row[cFree8].ToString() });
if (srow == null)
{
dtNew.Rows.Add(row.ItemArray);
}
else
{
srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
}
}
return dtNew;
}
#endregion
#region 现
public static DataTable MergeDataTableX(DataTable dt, string AuotID, string cBatch, string iQuantity, string cInvCode, string iNum, SqlCommand cmd)
{
DataTable dtNew = dt.Clone();
dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[cInvCode], dtNew.Columns[cBatch] };
foreach (DataRow row in dt.Rows)
{
if (string.IsNullOrEmpty(cBatch))
{
cBatch = "";
}
if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
{
row[cBatch] = "";
}
DataRow srow = dtNew.Rows.Find(new object[] { row[cInvCode].ToString(), row[cBatch].ToString() });
if (srow == null)
{
dtNew.Rows.Add(row.ItemArray);
}
else
{
srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
srow[iNum] = decimal.Parse(srow[iNum].ToString()) + decimal.Parse(row[iNum].ToString());
}
}
return dtNew;
}
public static DataTable MergeDataTable(DataTable dt, string AuotID, string cBatch, string iQuantity, string cInvCode, string iNum, SqlCommand cmd)
{
DataTable dtNew = dt.Clone();
//dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[AuotID], dtNew.Columns[cInvCode], dtNew.Columns[cBatch] };
dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[AuotID], dtNew.Columns[cBatch] };//原
foreach (DataRow row in dt.Rows)
{
if (string.IsNullOrEmpty(cBatch))
{
cBatch = "";
}
if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
{
row[cBatch] = "";
}
DataRow srow = dtNew.Rows.Find(new object[] { row[AuotID].ToString(), row[cBatch].ToString() });
//DataRow srow = dtNew.Rows.Find(new object[] { row[AuotID].ToString(), dtNew.Columns[cInvCode], row[cBatch].ToString() });
if (srow == null)
{
dtNew.Rows.Add(row.ItemArray);
}
else
{
srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
srow[iNum] = decimal.Parse(srow[iNum].ToString()) + decimal.Parse(row[iNum].ToString());
}
}
return dtNew;
}
public static DataTable MergeRd09(DataTable dt, string cBatch, string iQuantity, string cInvCode, string iNum, SqlCommand cmd)
{
DataTable dtNew = dt.Clone();
dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[cInvCode], dtNew.Columns[cBatch] };
foreach (DataRow row in dt.Rows)
{
if (string.IsNullOrEmpty(cBatch))
{
cBatch = "";
}
if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
{
row[cBatch] = "";
}
DataRow srow = dtNew.Rows.Find(new object[] { row[cInvCode].ToString(), row[cBatch].ToString() });
if (srow == null)
{
dtNew.Rows.Add(row.ItemArray);
}
else
{
srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
srow[iNum] = decimal.Parse(srow[iNum].ToString()) + decimal.Parse(row[iNum].ToString());
}
}
return dtNew;
}
#endregion
public static IList<T> ConvertTo<T>(DataTable table)
{
if (table == null)
{
return null;
}
List<DataRow> rows = new List<DataRow>();
foreach (DataRow row in table.Rows)
{
rows.Add(row);
}
return ConvertTo<T>(rows);
}
public static IList<T> ConvertTo<T>(IList<DataRow> rows)
{
IList<T> list = null;
if (rows != null)
{
list = new List<T>();
foreach (DataRow row in rows)
{
T item = CreateItem<T>(row);
list.Add(item);
}
}
return list;
}
public static T CreateItem<T>(DataRow row)
{
T obj = default(T);
if (row != null)
{
obj = Activator.CreateInstance<T>();
foreach (DataColumn column in row.Table.Columns)
{
PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
try
{
object value = row[column.ColumnName];
prop.SetValue(obj, value, null);
}
catch
{ //You can log something here
//throw;
}
}
}
return obj;
}
public static DataTable MergeDataTable(DataTable dt, string AuotID, string iQuantity, string cBatch)
{
DataTable dtNew = dt.Clone();
dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[AuotID] };
foreach (DataRow row in dt.Rows)
{
DataRow srow = dtNew.Rows.Find(new object[] { row[AuotID].ToString() });
if (srow == null)
{
dtNew.Rows.Add(row.ItemArray);
}
else
{
srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
}
}
return dtNew;
}
#region 返回默认的出入库类别
/// <summary>
/// 返回默认的出入库类别
/// </summary>
/// <returns></returns>
public static string returnDefaultRdType(string VTID, string BTChName, SqlCommand cmd)
{
string sql = @"select VouchRdContrapose.cVRGUID,cVTChName,cBTChName,cVRRCode,R.cRdName,cVRSCode,S.cRdName
from VouchRdContrapose with(nolock)
left join vouchTypeDic with(nolock) on VouchRdContrapose.cVBTID=VouchTypeDic.cVBTID
left join Rd_Style as R with(nolock) On cVRRCode=R.cRdCode and R.bRDFlag=1
left join Rd_Style as S with(nolock) ON cVRSCode=S.cRdCode and S.bRDFlag=0
where 1=1 And (cVTID = N'{0}') And (cBTChName = N'{1}') order by cSerial ";
sql = string.Format(sql, VTID, BTChName);
DataTable dt = SQlReturnData(sql, cmd);
if (dt.Rows.Count == 0)
{
throw new Exception("倒冲材料出库单的出库类别取得失败");
}
return dt.Rows[0]["cVRSCode"].ToString();
}
#endregion
public static string sqltext(string cInvCode, string cBatch, string cFree1, string cFree2, string cFree3, string cFree4, string cFree5, string cFree6, string cFree7, string cFree8, SqlCommand cmd)
{
string sql = "";
if (DBHelper.bInvBatch(cInvCode, cmd) == true)
sql += " and cBatch='" + cBatch + "' ";
else
sql += " and cBatch='' ";
if (DBHelper.bFree1(cInvCode, cmd) == true)
sql += " and cFree1='" + cFree1 + "' ";
else
sql += " and cFree1='' ";
if (DBHelper.bFree2(cInvCode, cmd) == true)
sql += " and cFree2='" + cFree2 + "' ";
else
sql += " and cFree2='' ";
if (DBHelper.bFree3(cInvCode, cmd) == true)
sql += " and cFree3='" + cFree3 + "' ";
else
sql += " and cFree3='' ";
if (DBHelper.bFree4(cInvCode, cmd) == true)
sql += " and cFree4='" + cFree4 + "' ";
else
sql += " and cFree4='' ";
if (DBHelper.bFree5(cInvCode, cmd) == true)
sql += " and cFree5='" + cFree5 + "' ";
else
sql += " and cFree5='' ";
if (DBHelper.bFree6(cInvCode, cmd) == true)
sql += " and cFree6='" + cFree6 + "' ";
else
sql += " and cFree6='' ";
if (DBHelper.bFree7(cInvCode, cmd) == true)
sql += " and cFree7='" + cFree7 + "' ";
else
sql += " and cFree7='' ";
if (DBHelper.bFree8(cInvCode, cmd) == true)
sql += " and cFree8='" + cFree8 + "' ";
else
sql += " and cFree8='' ";
return sql;
}
public static string sqlnew(string cInvCode, string cBatch, string cFree1, string cFree2, string cFree3, string cFree4, string cFree5, string cFree6, string cFree7, string cFree8, SqlCommand cmd)
{
bool bFree1 = false;
bool bFree2 = false;
bool bFree3 = false;
bool bFree4 = false;
bool bFree5 = false;
bool bFree6 = false;
bool bFree7 = false;
bool bFree8 = false;
#region 自由项管控
DataTable SubdtFree = DBHelper.bFree(cInvCode, cmd);
if (SubdtFree.Rows.Count > 0 && SubdtFree != null)
{
bFree1 = Convert.ToBoolean(SubdtFree.Rows[0]["bFree1"]);
bFree2 = Convert.ToBoolean(SubdtFree.Rows[0]["bFree2"]);
bFree3 = Convert.ToBoolean(SubdtFree.Rows[0]["bFree3"]);
bFree4 = Convert.ToBoolean(SubdtFree.Rows[0]["bFree4"]);
bFree5 = Convert.ToBoolean(SubdtFree.Rows[0]["bFree5"]);
bFree6 = Convert.ToBoolean(SubdtFree.Rows[0]["bFree6"]);
bFree7 = Convert.ToBoolean(SubdtFree.Rows[0]["bFree7"]);
bFree8 = Convert.ToBoolean(SubdtFree.Rows[0]["bFree8"]);
}
else
{
throw new Exception("存货编码:" + cInvCode + "不存在");
}
#endregion
string sql = "";
if (DBHelper.bInvBatch(cInvCode, cmd) == true)
sql += " and cBatch='" + cBatch + "' ";
else
sql += " and cBatch='' ";
if (bFree1)
{
sql += " and cFree1='" + cFree1 + "' ";
}
else
{
sql += " and cFree1='' ";
}
if (bFree2)
{
sql += " and cFree2='" + cFree2 + "' ";
}
else
{
sql += " and cFree2='' ";
}
if (bFree3)
{
sql += " and cFree3='" + cFree3 + "' ";
}
else
{
sql += " and cFree3='' ";
}
if (bFree4)
{
sql += " and cFree4='" + cFree4 + "' ";
}
else
{
sql += " and cFree4='' ";
}
if (bFree5)
{
sql += " and cFree5='" + cFree5 + "' ";
}
else
{
sql += " and cFree5='' ";
}
if (bFree6)
{
sql += " and cFree6='" + cFree6 + "' ";
}
else
{
sql += " and cFree6='' ";
}
if (bFree7)
{
sql += " and cFree7='" + cFree7 + "' ";
}
else
{
sql += " and cFree7='' ";
}
if (bFree8)
{
sql += " and cFree8='" + cFree8 + "' ";
}
else
{
sql += " and cFree8='' ";
}
return sql;
}
/// <summary>
/// 方法一:获取编号 返回Dictionary字典,调用该方法用Dictionary字典接收,只需要遍历Dictionary即可得到响应的值
/// </summary>
/// <param name="workPointCode"></param>
/// <param name="tbName"></param>
/// <param name="colName"></param>
/// <param name="Pre"></param>
/// <param name="numLen"></param>
/// <returns>返回Dictionary字典</returns>
public static Dictionary<string, int> GetAllCode(string cAcc_Id, string cVouchType, string iAmount)
{
string iFatherId = string.Empty, iChildId = string.Empty;
Dictionary<string, int> dic = new Dictionary<string, int>();
try
{
SqlConnection conn = new SqlConnection(ERPConnString);
SqlCommand cmd = new SqlCommand("sp_GetIDWithoutRemote", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@cAcc_Id", cAcc_Id);  //给输入参数赋值
cmd.Parameters.AddWithValue("@cVouchType", cVouchType);  //给输入参数赋值
cmd.Parameters.AddWithValue("@iAmount", iAmount);  //给输入参数赋值
//cmd.Parameters.AddWithValue("@iFatherId", iFatherId);  //给输入参数赋值
//cmd.Parameters.AddWithValue("@iChildId", iChildId);  //给输入参数赋值
SqlParameter parOutput = cmd.Parameters.Add("@iFatherId", SqlDbType.NVarChar, 50);  //定义输出参数
cmd.Parameters["@iFatherId"].Direction = ParameterDirection.Output;
SqlParameter parOutputs = cmd.Parameters.Add("@iChildId", SqlDbType.NVarChar, 50);  //定义输出参数
cmd.Parameters["@iChildId"].Direction = ParameterDirection.Output;
SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int);
parReturn.Direction = ParameterDirection.ReturnValue;   //参数类型为ReturnValue
cmd.Parameters.Add(parReturn);
conn.Open();
cmd.ExecuteNonQuery();
iFatherId = cmd.Parameters["@iFatherId"].Value.ToString();
iChildId = cmd.Parameters["@iChildId"].Value.ToString();
if (!string.IsNullOrWhiteSpace(iFatherId))//判断iFatherId是否为空,不为空的话将值放入dictionary字典中,否则int.Parse()会抛出异常
{
dic.Add("iFatherId", int.Parse(iFatherId));
dic.Add("iChildId", int.Parse(iChildId));
}
}
catch (System.Exception ex)
{
throw ex;
}
return dic;
}
/// <summary>
/// 方法二 使用输出参数值
/// </summary>
/// <param name="cAcc_Id"></param>
/// <param name="cVouchType"></param>
/// <param name="iAmount"></param>
/// <returns></returns>
public static void GetAllCode(string cAcc_Id, string cVouchType, string iAmount, out int iFatherId, out int iChildId)
{
try
{
iFatherId = 0; iChildId = 0;
SqlConnection conn = new SqlConnection(ERPConnString);
SqlCommand cmd = new SqlCommand("sp_GetIDWithoutRemote", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@cAcc_Id", cAcc_Id);  //给输入参数赋值
cmd.Parameters.AddWithValue("@cVouchType", cVouchType);  //给输入参数赋值
cmd.Parameters.AddWithValue("@iAmount", iAmount);  //给输入参数赋值
//cmd.Parameters.AddWithValue("@iFatherId", iFatherId);  //给输入参数赋值
//cmd.Parameters.AddWithValue("@iChildId", iChildId);  //给输入参数赋值
SqlParameter parOutput = cmd.Parameters.Add("@iFatherId", SqlDbType.NVarChar, 50);  //定义输出参数
cmd.Parameters["@iFatherId"].Direction = ParameterDirection.Output;
SqlParameter parOutputs = cmd.Parameters.Add("@iChildId", SqlDbType.NVarChar, 50);  //定义输出参数
cmd.Parameters["@iChildId"].Direction = ParameterDirection.Output;
//SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int);
//parReturn.Direction = ParameterDirection.ReturnValue;   //参数类型为ReturnValue
//cmd.Parameters.Add(parReturn);
conn.Open();
cmd.ExecuteNonQuery();
string _iFatherId = cmd.Parameters["@iFatherId"].Value.ToString();
string _iChildId = cmd.Parameters["@iChildId"].Value.ToString();
if (!string.IsNullOrWhiteSpace(_iFatherId))
{
iFatherId = int.Parse(_iFatherId);
}
if (!string.IsNullOrWhiteSpace(_iChildId))
{
iChildId = int.Parse(_iChildId);
}
}
catch (System.Exception ex)
{
throw ex;
}
}
/// <summary>
/// 方法二 使用输出参数值
/// </summary>
/// <param name="cAcc_Id"></param>
/// <param name="cVouchType"></param>
/// <param name="iAmount"></param>
/// <returns></returns>
public static string GetAllRDCode(string CardNumber, string dDate, string UserCode)
{
string iBaseCodeLen = string.Empty; string cVouchCodeBase = string.Empty;
Dictionary<string, int> dic = new Dictionary<string, int>();
try
{
SqlConnection conn = new SqlConnection(ERPConnString);
SqlCommand cmd = new SqlCommand("ICS_VoucherNumber", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CardNumber", CardNumber);  //给输入参数赋值
cmd.Parameters.AddWithValue("@dDate", dDate);  //给输入参数赋值
cmd.Parameters.AddWithValue("@UserCode", UserCode);  //给输入参数赋值
SqlParameter parOutput = cmd.Parameters.Add("@number", SqlDbType.NVarChar, 50);  //定义输出参数
parOutput.Direction = ParameterDirection.Output;
//SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int);
//parReturn.Direction = ParameterDirection.ReturnValue;   //参数类型为ReturnValue
//cmd.Parameters.Add(parReturn);
conn.Open();
cmd.ExecuteNonQuery();
return parOutput.Value.ToString();
//iBaseCodeLen = cmd.Parameters["@iBaseCodeLen"].Value.ToString();
// cVouchCodeBase = cmd.Parameters["@cVouchCodeBase"].Value.ToString();
//UserCode= cmd.Parameters["@cVouchCodePreFix"].Value.ToString();
////if (!string.IsNullOrWhiteSpace(iBaseCodeLen))//判断iFatherId是否为空,不为空的话将值放入dictionary字典中,否则int.Parse()会抛出异常
////{
//// dic.Add("iBaseCodeLen", int.Parse(iBaseCodeLen));
////}
////else
////{
//// dic.Add("cVouchCodeBase", int.Parse(cVouchCodeBase));
// UserCode= UserCode + (cVouchCodeBase.ToString().PadLeft(int.Parse(iBaseCodeLen), '0'));
////}
}
catch (System.Exception ex)
{
throw ex;
}
//return UserCode;
}
public static string GetRDCode(string RDName,SqlCommand cmd)
{
string sql = @"select cRdCode from Rd_Style where cRdName='{0}'";
sql = string.Format(sql,RDName);
DataTable dt = SQlReturnData(sql,cmd);
return dt.Rows[0]["cRdCode"].ToString();
}
/// <summary>
/// DataSet转Json字符串,主子结构
/// 需要建立主子表关系,第一张表为主表
/// 会排除关联列
/// </summary>
/// <param name="dataSet"></param>
/// <param name="RelationName">关系名称</param>
/// <returns></returns>
public static string DataSetToJson(DataSet dataSet, string RelationName)
{
StringBuilder jsonString = new StringBuilder();
//foreach (DataTable table in dataSet.Tables)
//{
DataTable table = dataSet.Tables[0];
jsonString.Append("[");
DataRowCollection drc = table.Rows;
for (int i = 0; i < drc.Count; i++)
{
DataRow dataRow = drc[i];
jsonString.Append("{");
for (int j = 0; j < table.Columns.Count; j++)
{
string strKey = table.Columns[j].ColumnName;
if (dataSet.Relations[RelationName].ParentColumns.Select(a => a.Caption).Contains(strKey))
continue;
string strValue = dataRow[j].ToString();
Type type = table.Columns[j].DataType;
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if (j < table.Columns.Count - 1)
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append(",\"" + RelationName + "\":");
DataRow[] drs = dataRow.GetChildRows(RelationName);
jsonString.Append("[");
foreach (DataRow dr in drs)
{
DataTable dt = dr.Table;
jsonString.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
string strKey = dt.Columns[j].ColumnName;
if (dataSet.Relations[RelationName].ChildColumns.Select(a => a.Caption).Contains(strKey))
continue;
string strValue = dr[j].ToString();
Type type = dt.Columns[j].DataType;
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if (j < dt.Columns.Count - 1)
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
if (drs.Length > 0)
jsonString.Remove(jsonString.Length - 1, 1);
jsonString.Append("]");
jsonString.Append("},");
}
jsonString.Remove(jsonString.Length - 1, 1);
jsonString.Append("]");
//}
string res = jsonString.ToString();
return res;
}
#region 私有方法
/// <summary>
/// 过滤特殊字符
/// </summary>
/// <param name="s">字符串</param>
/// <returns>json字符串</returns>
private static string String2Json(String s)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
char c = s.ToCharArray()[i];
switch (c)
{
case '\"':
sb.Append("\\\""); break;
case '\\':
sb.Append("\\\\"); break;
case '/':
sb.Append("\\/"); break;
case '\b':
sb.Append("\\b"); break;
case '\f':
sb.Append("\\f"); break;
case '\n':
sb.Append("\\n"); break;
case '\r':
sb.Append("\\r"); break;
case '\t':
sb.Append("\\t"); break;
default:
sb.Append(c); break;
}
}
return sb.ToString();
}
/// <summary>
/// 格式化字符型、日期型、布尔型
/// </summary>
/// <param name="str"></param>
/// <param name="type"></param>
/// <returns></returns>
private static string StringFormat(string str, Type type)
{
if (type == typeof(string))
{
str = String2Json(str);
str = "\"" + str + "\"";
}
else if (type == typeof(DateTime))
{
str = "\"" + str + "\"";
}
else if (type == typeof(bool))
{
str = str.ToLower();
}
else if (type != typeof(string) && string.IsNullOrEmpty(str))
{
str = "\"" + str + "\"";
}
return str;
}
#endregion
public static DataSet SQlReturnDataSet(string SQl, SqlCommand cmd)
{
DataSet ds = new DataSet();
SqlDataAdapter dr = new System.Data.SqlClient.SqlDataAdapter();
cmd.CommandText = SQl;
dr.SelectCommand = cmd;
dr.Fill(ds);
return ds;
}
/// <summary>
/// 获取用户的姓名与部门
/// </summary>
/// <param name="cPer_Num">用户编号</param>
/// <param name="cmd"></param>
/// <returns></returns>
public static ICSUserInfo GetPersonInfo(string cPer_Num, SqlCommand cmd)
{
ICSUserInfo person = new ICSUserInfo();
string sql = @" exec sp_refreshview ua_user ;
SELECT a.cUser_Id,a.cUser_Name,b.cDepCode FROM ua_user a
LEFT JOIN dbo.Department b ON a.cDept=b.cDepName
WHERE cUser_Id ='" + cPer_Num + "'";
cmd.CommandText = sql;
DataTable dt = SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
person.DepCode = dt.Rows[0]["cDepCode"].ToString();
person.UserName = dt.Rows[0]["cUser_Name"].ToString();
person.UserCode = cPer_Num;
}
else
throw new Exception("ERP人员不存在,编码:" + cPer_Num);
return person;
}
}
}