纽威
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

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. using ICSSoft.Entity;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Configuration;
  5. using System.Data;
  6. using System.Data.Common;
  7. using System.Data.SqlClient;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using ICSSoft.Entity;
  13. namespace ICSSoft.Common
  14. {
  15. public class DBHelper
  16. {
  17. private static log4net.ILog log = log4net.LogManager.GetLogger("U8Helper");
  18. private static string connString = System.Configuration.ConfigurationManager.AppSettings["ConnStr"];
  19. private static string ERPConnString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];
  20. private static string ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"];
  21. //// 访问数据库所需要的适配器
  22. //public static string connString = AppConfig.StrConnection;
  23. ///// <summary>
  24. ///// 根据查询语句获取一个DataTable,对异常捕获无指定要求
  25. ///// </summary>
  26. ///// <param name="select">查询语句</param>
  27. ///// <returns>所查询数据</returns>
  28. //public static DataTable GetDataTable(string select)
  29. //{
  30. // using (SqlConnection m_cnn = new SqlConnection(connString))
  31. // {
  32. // DataTable dt = new DataTable();
  33. // SqlDataAdapter m_da = new SqlDataAdapter(select, m_cnn);
  34. // m_da.SelectCommand.CommandTimeout = 600;
  35. // m_da.SelectCommand.CommandType = CommandType.Text;
  36. // m_da.SelectCommand.CommandText = select;
  37. // m_da.Fill(dt);
  38. // return dt;
  39. // }
  40. //}
  41. /// <summary>
  42. /// 事物取DataTable
  43. /// </summary>
  44. /// <param name="SQl"></param>
  45. /// <param name="cmd"></param>
  46. /// <returns></returns>
  47. public static DataTable SQlReturnData(string SQl, SqlCommand cmd)
  48. {
  49. DataTable dt = new DataTable();
  50. SqlDataAdapter dr = new System.Data.SqlClient.SqlDataAdapter();
  51. cmd.CommandText = SQl;
  52. dr.SelectCommand = cmd;
  53. dr.Fill(dt);
  54. return dt;
  55. }
  56. /// <summary>
  57. /// 依靠数据库连接字符串connectionString,
  58. /// 使用所提供参数,执行返回首行首列命令
  59. /// </summary>
  60. /// <param name="commandType">执行命令的类型(存储过程或T-SQL,等等)</param>
  61. /// <param name="commandText">存储过程名称或者T-SQL命令行</param>
  62. /// <returns>返回一个对象,使用Convert.To{Type}将该对象转换成想要的数据类型。</returns>
  63. public static object ExecuteScalar(CommandType cmdType, string cmdText, string conn)
  64. {
  65. try
  66. {
  67. DbCommand cmd = CreateDbCommand();
  68. using (DbConnection connection = CreateDbConnection(conn))
  69. {
  70. PrepareCommand(cmd, connection, null, cmdType, cmdText, null);
  71. object val = cmd.ExecuteScalar();
  72. cmd.Parameters.Clear();
  73. return val;
  74. }
  75. }
  76. catch (Exception ex)
  77. {
  78. //log.Error(ex.Message);
  79. throw;
  80. }
  81. }
  82. /// <summary>
  83. /// 为即将执行准备一个命令
  84. /// </summary>
  85. /// <param name="cmd">SqlCommand对象</param>
  86. /// <param name="conn">SqlConnection对象</param>
  87. /// <param name="isOpenTrans">DbTransaction对象</param>
  88. /// <param name="cmdType">执行命令的类型(存储过程或T-SQL,等等)</param>
  89. /// <param name="cmdText">存储过程名称或者T-SQL命令行, e.g. Select * from Products</param>
  90. /// <param name="cmdParms">SqlParameters to use in the command</param>
  91. private static void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction isOpenTrans, CommandType cmdType, string cmdText, DbParameter[] cmdParms)
  92. {
  93. if (conn.State != ConnectionState.Open)
  94. conn.Open();
  95. cmd.Connection = conn;
  96. cmd.CommandText = cmdText;
  97. if (isOpenTrans != null)
  98. cmd.Transaction = isOpenTrans;
  99. cmd.CommandType = cmdType;
  100. if (cmdParms != null)
  101. {
  102. cmd.Parameters.AddRange(cmdParms);
  103. }
  104. }
  105. /// <summary>
  106. /// 数据库类型
  107. /// </summary>
  108. public static DatabaseType DbType { get; set; }
  109. /// <summary>
  110. /// 根据配置文件中所配置的数据库类型和传入的
  111. /// 数据库链接字符串来创建相应数据库连接对象
  112. /// </summary>
  113. /// <param name="connectionString"></param>
  114. /// <returns></returns>
  115. public static DbConnection CreateDbConnection(string connectionString)
  116. {
  117. DbConnection conn = null;
  118. switch (DbType)
  119. {
  120. case DatabaseType.SqlServer:
  121. conn = new SqlConnection(connectionString);
  122. break;
  123. //case DatabaseType.Oracle:
  124. // conn = new OracleConnection(connectionString);
  125. // break;
  126. //case DatabaseType.MySql:
  127. // conn = new MySqlConnection(connectionString);
  128. // break;
  129. //case DatabaseType.Access:
  130. // conn = new OleDbConnection(connectionString);
  131. // break;
  132. //case DatabaseType.SQLite:
  133. // conn = new SQLiteConnection(connectionString);
  134. // break;
  135. default:
  136. throw new Exception("数据库类型目前不支持!");
  137. }
  138. return conn;
  139. }
  140. /// <summary>
  141. /// 根据配置文件中所配置的数据库类型
  142. /// 来创建相应数据库命令对象
  143. /// </summary>
  144. /// <returns></returns>
  145. public static DbCommand CreateDbCommand()
  146. {
  147. DbCommand cmd = null;
  148. switch (DbType)
  149. {
  150. case DatabaseType.SqlServer:
  151. cmd = new SqlCommand();
  152. break;
  153. //case DatabaseType.Oracle:
  154. // cmd = new OracleCommand();
  155. // break;
  156. //case DatabaseType.MySql:
  157. // cmd = new MySqlCommand();
  158. // break;
  159. //case DatabaseType.Access:
  160. // cmd = new OleDbCommand();
  161. // break;
  162. //case DatabaseType.SQLite:
  163. // cmd = new SQLiteCommand();
  164. // break;
  165. default:
  166. throw new Exception("数据库类型目前不支持!");
  167. }
  168. return cmd;
  169. }
  170. public enum DatabaseType
  171. {
  172. /// <summary>
  173. /// 数据库类型:Oracle
  174. /// </summary>
  175. Oracle,
  176. /// <summary>
  177. /// 数据库类型:SqlServer
  178. /// </summary>
  179. SqlServer,
  180. /// <summary>
  181. /// 数据库类型:Access
  182. /// </summary>
  183. Access,
  184. /// <summary>
  185. /// 数据库类型:MySql
  186. /// </summary>
  187. MySql,
  188. /// <summary>
  189. /// 数据库类型:SQLite
  190. /// </summary>
  191. SQLite
  192. }
  193. public static bool ExecuteNonQuery(string sql, SqlCommand cmd)
  194. {
  195. try
  196. {
  197. cmd.CommandText = sql;
  198. int result = cmd.ExecuteNonQuery();
  199. if (result > 0)
  200. {
  201. return true;
  202. }
  203. else
  204. {
  205. log.Info("SQL执行受影响行数<0;" + sql);
  206. return false;
  207. }
  208. }
  209. catch (Exception ex)
  210. {
  211. string Params = string.Empty;
  212. foreach (SqlParameter parameter in cmd.Parameters)
  213. {
  214. Params += parameter.SqlValue + "||";
  215. }
  216. log.Error("异常:" + ex.Message + ";\r\n SQL:" + sql + "参数:" + Params);
  217. throw new Exception("程序异常!");
  218. }
  219. }
  220. /// <summary>
  221. /// 获取插入单据的表头表体最大ID
  222. /// </summary>
  223. /// <param name="IDtype"></param>
  224. /// <param name="cAcc_id"></param>
  225. /// <param name="rowCount"></param>
  226. /// <param name="id"></param>
  227. /// <param name="did"></param>
  228. public static void SaveGetrdIDandDID(string IDtype, string cAcc_id, int rowCount, out int id, out int did, SqlCommand cmd)
  229. {
  230. cmd.Parameters.Clear();
  231. try
  232. {
  233. string[] ss = cAcc_id.Split('_');
  234. string ErpCount = ss[1];
  235. string str = @"DECLARE @ID int
  236. DECLARE @DID int
  237. SET @ID = 0
  238. SET @DID = 0
  239. IF NOT EXISTS (SELECT * FROM UFSystem..ua_identity WHERE cacc_id = '{0}' AND cVouchType = '{1}')
  240. BEGIN
  241. INSERT INTO UFSystem..ua_identity(cAcc_Id,cVouchType,iFatherId,iChildId) VALUES('{0}','{1}',1,1)
  242. END
  243. ELSE
  244. BEGIN
  245. UPDATE UFSystem..ua_identity
  246. SET ifatherID = ifatherID +1,ichildID = ichildID + {2}
  247. WHERE cVouchType = '{1}' AND cAcc_id = '{0}'
  248. END
  249. select ifatherID as ID,ichildID as DID FROM UFSystem..ua_identity WHERE cVouchType = '{1}' AND cAcc_id = '{0}' ";
  250. str = string.Format(str, ErpCount, IDtype, rowCount.ToString());
  251. DataTable dt = SQlReturnData(str, cmd);
  252. if (dt.Rows.Count == 0)
  253. {
  254. throw new Exception("ID取得失败");
  255. }
  256. id = Convert.ToInt32(dt.Rows[0]["ID"]);
  257. did = Convert.ToInt32(dt.Rows[0]["DID"]);
  258. #region 测试时屏蔽
  259. // if (IDtype == "rd")
  260. // {
  261. // 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 (
  262. // SELECT MAX(ID) AS ID,MAX(AutoID) AS DID FROM rdrecords01
  263. // UNION
  264. // SELECT MAX(ID) AS ID,MAX(AutoID) AS DID FROM rdrecords08
  265. // UNION
  266. // SELECT MAX(ID) AS ID,MAX(AutoID) AS DID FROM rdrecords09
  267. // UNION
  268. // SELECT MAX(ID) AS ID,MAX(AutoID) AS DID FROM rdrecords10
  269. // UNION
  270. // SELECT MAX(ID) AS ID,MAX(AutoID) AS DID FROM rdrecords11
  271. // UNION
  272. // SELECT MAX(ID) AS ID,MAX(AutoID) AS DID FROM rdrecords32
  273. // ) a";
  274. // DataTable dtCheck = SQlReturnData(sql, cmd);
  275. // if (dtCheck != null && dtCheck.Rows.Count > 0)
  276. // {
  277. // if (id <= Convert.ToInt32(dtCheck.Rows[0]["ID"].ToString()) || did <= Convert.ToInt32(dtCheck.Rows[0]["DID"].ToString()))
  278. // {
  279. // id = Convert.ToInt32(dtCheck.Rows[0]["ID"].ToString()) + 1;
  280. // did = Convert.ToInt32(dtCheck.Rows[0]["DID"].ToString()) + 1;
  281. // sql = string.Format(@" UPDATE UFSystem..ua_identity
  282. // SET ifatherID = {0}, ichildID = {1}
  283. // WHERE cVouchType = '{2}' AND cAcc_id = '{3}' ", id, did, IDtype, ErpCount);
  284. // cmd.CommandText = sql;
  285. // int i = cmd.ExecuteNonQuery();
  286. // }
  287. // }
  288. // }
  289. #endregion
  290. }
  291. catch (Exception ex)
  292. {
  293. throw new Exception(ex.Message);
  294. }
  295. }
  296. public static void SaveGetrdIDandDIDs(string IDtype, string cAcc_id, int rowCount, out int id, out int did, SqlCommand cmd)
  297. {
  298. cmd.Parameters.Clear();
  299. try
  300. {
  301. string[] ss = cAcc_id.Split('_');
  302. string ErpCount = ss[1];
  303. string str = @"DECLARE @ID int
  304. DECLARE @DID int
  305. SET @ID = 0
  306. SET @DID = 0
  307. IF NOT EXISTS (SELECT * FROM UFSystem..ua_identity WHERE cacc_id = '{0}' AND cVouchType = '{1}')
  308. BEGIN
  309. INSERT INTO UFSystem..ua_identity(cAcc_Id,cVouchType,iFatherId,iChildId) VALUES('{0}','{1}',1,1)
  310. END
  311. ELSE
  312. BEGIN
  313. UPDATE UFSystem..ua_identity SET ichildID = ichildID + {2}
  314. WHERE cVouchType = '{1}' AND cAcc_id = '{0}'
  315. END
  316. select ifatherID as ID,ichildID as DID FROM UFSystem..ua_identity WHERE cVouchType = '{1}' AND cAcc_id = '{0}' ";
  317. str = string.Format(str, ErpCount, IDtype, rowCount.ToString());
  318. DataTable dt = SQlReturnData(str, cmd);
  319. if (dt.Rows.Count == 0)
  320. {
  321. throw new Exception("ID取得失败");
  322. }
  323. id = Convert.ToInt32(dt.Rows[0]["ID"]);
  324. did = Convert.ToInt32(dt.Rows[0]["DID"]);
  325. }
  326. catch (Exception ex)
  327. {
  328. throw new Exception(ex.Message);
  329. }
  330. }
  331. /// <summary>
  332. /// 更新主键ID
  333. /// </summary>
  334. /// <param name="IDtype"></param>
  335. /// <param name="cAcc_id"></param>
  336. /// <param name="rowCount"></param>
  337. public static void UpdateIDandDID(string IDtype, string cAcc_id, int rowCount, SqlCommand cmd)
  338. {
  339. try
  340. {
  341. string[] ss = cAcc_id.Split('_');
  342. string ErpCount = ss[1];
  343. string sql = @" UPDATE UFSystem..ua_identity
  344. SET ifatherID = ifatherID +1,ichildID = ichildID + {2}
  345. WHERE cVouchType = '{1}' AND cAcc_id = '{0}' ";
  346. sql = string.Format(sql, ErpCount, IDtype, rowCount.ToString());
  347. cmd.CommandText = sql;
  348. int i = cmd.ExecuteNonQuery();
  349. if (i <= 0)
  350. {
  351. throw new Exception("更新主键ID,DID失败!");
  352. }
  353. }
  354. catch (Exception ex)
  355. {
  356. throw new Exception(ex.Message);
  357. }
  358. }
  359. //public static int ExecuteSql(string sqlUpdate)
  360. //{
  361. // using (SqlConnection conn = new SqlConnection(connString))
  362. // {
  363. // try
  364. // {
  365. // SqlCommand cmd = new SqlCommand();
  366. // cmd.CommandText = sqlUpdate;
  367. // if (conn.State != ConnectionState.Open)
  368. // {
  369. // conn.Open();
  370. // }
  371. // cmd.Connection = conn;
  372. // return cmd.ExecuteNonQuery();
  373. // }
  374. // catch (Exception ex)
  375. // {
  376. // throw new Exception(ex.Message);
  377. // }
  378. // finally
  379. // {
  380. // if (conn.State != ConnectionState.Closed)
  381. // {
  382. // conn.Close();
  383. // }
  384. // }
  385. // }
  386. //}
  387. /// <summary>
  388. /// 执行Insert 或者 Update
  389. /// </summary>
  390. /// <param name="sql"></param>
  391. /// <param name="cmd"></param>
  392. /// <param name="message"></param>
  393. public static void CmdExecuteNonQuery(string sql, SqlCommand cmd, string message)
  394. {
  395. try
  396. {
  397. cmd.CommandText = sql;
  398. int count = cmd.ExecuteNonQuery();
  399. if (count <= 0)
  400. {
  401. string Msg = string.Empty;
  402. foreach (SqlParameter parameter in cmd.Parameters)
  403. {
  404. Msg += "参数名:" + parameter.ParameterName + "参数值:" + parameter.Value;
  405. }
  406. log.Info("受影响行数小于0;" + sql + "\r\n" + Msg);
  407. throw new Exception(message);
  408. }
  409. }
  410. catch (Exception ex)
  411. {
  412. string Msg = string.Empty;
  413. foreach (SqlParameter parameter in cmd.Parameters)
  414. {
  415. Msg += "参数名:" + parameter.ParameterName + "参数值:" + parameter.Value;
  416. }
  417. log.Info("异常:" + ex.Message + "\r\n " + message + "\r\n SQL:" + sql + "\r\n" + Msg);
  418. throw new Exception(message + Environment.NewLine + ex.Message);
  419. }
  420. }
  421. /// <summary>
  422. /// 1 取得单据的默认模板
  423. /// </summary>
  424. /// <param name="ErpName">账套名</param>
  425. /// <param name="CardNumber"></param>
  426. /// <param name="cmd"></param>
  427. /// <returns></returns>
  428. public static string GetDefaultTemplate( string CardNumber, SqlCommand cmd)
  429. {
  430. try
  431. {
  432. string sql = "";
  433. string VouchDEF_ID = string.Empty;
  434. sql = string.Format("SELECT DEF_ID FROM Vouchers WHERE CardNumber = '{0}' ", CardNumber);
  435. cmd.CommandText = sql;
  436. DataTable dtDEF_ID = SQlReturnData(sql, cmd);
  437. if (dtDEF_ID != null && dtDEF_ID.Rows.Count > 0)
  438. {
  439. VouchDEF_ID = dtDEF_ID.Rows[0]["DEF_ID"].ToString();
  440. }
  441. else
  442. {
  443. throw new Exception("获取默认显示模板失败!" + sql);
  444. }
  445. return VouchDEF_ID;
  446. }
  447. catch (Exception ex)
  448. {
  449. throw new Exception(ex.Message);
  450. }
  451. }
  452. /// <summary>
  453. /// 2 取得单据的表头ID,表体DID
  454. /// </summary>
  455. /// <param name="VouchType">单据类型 如“rd”</param>
  456. /// <param name="ErpName">账套名</param>
  457. /// <param name="RowCount">表体行</param>
  458. /// <returns></returns>
  459. public static VouchKey GetPrimaryKey(string VouchType, string ErpName, int RowCount, SqlCommand cmd)
  460. {
  461. try
  462. {
  463. string num = "1000000000";
  464. int id = 0;
  465. int did = 0;
  466. VouchKey model = new VouchKey();
  467. SaveGetrdIDandDID(VouchType, ErpName, RowCount, out id, out did, cmd);
  468. model.ID = int.Parse(num.Substring(0, 10 - (id.ToString().Length)) + id.ToString());
  469. model.DID = int.Parse(num.Substring(0, 10 - (did.ToString().Length)) + did.ToString());
  470. return model;
  471. }
  472. catch (Exception ex)
  473. {
  474. throw new Exception(ex.Message);
  475. }
  476. }
  477. public static VouchKey GetPrimaryKeys(string VouchType, string ErpName, int RowCount, SqlCommand cmd)
  478. {
  479. try
  480. {
  481. string num = "1000000000";
  482. int id = 0;
  483. int did = 0;
  484. VouchKey model = new VouchKey();
  485. SaveGetrdIDandDIDs(VouchType, ErpName, RowCount, out id, out did, cmd);
  486. model.DID = int.Parse(num.Substring(0, 10 - (did.ToString().Length)) + did.ToString());
  487. return model;
  488. }
  489. catch (Exception ex)
  490. {
  491. throw new Exception(ex.Message);
  492. }
  493. }
  494. /// <summary>
  495. /// 3 取得单据编号
  496. /// </summary>
  497. /// <param name="ErpName">账套名</param>
  498. /// <param name="CardNumber"></param>
  499. /// <param name="PreStr">单据前缀</param>
  500. /// <param name="cmd"></param>
  501. /// <returns></returns>
  502. public static int GetVouchCode(string ErpName, string CardNumber, string PreStr, string TableName, SqlCommand cmd)
  503. {
  504. string sql = "";
  505. sql = string.Format("select * from {0}.dbo.VoucherHistory where cSeed = Substring(Convert( varchar(100),GetDate(),112),3,4) and CardNumber = '{1}'", ErpName, CardNumber);
  506. DataTable dt = SQlReturnData(sql, cmd);
  507. if (dt != null && dt.Rows.Count > 0)
  508. {
  509. sql = string.Format(@"UPDATE {0}.dbo.VoucherHistory SET cNumber =cast(( cast(cNumber as int)+1) as nvarchar(30))
  510. WHERE cSeed = SUBSTRING(CONVERT(varchar(100), GETDATE(), 112),3,4) AND CardNumber = '{1}'", ErpName, CardNumber);
  511. CmdExecuteNonQuery(sql, cmd, "更新VoucherHistory表失败!");
  512. }
  513. else
  514. {
  515. sql = string.Format(@"INSERT INTO {0}.dbo.VoucherHistory
  516. SELECT '{1}',NULL,'','',SUBSTRING(CONVERT(varchar(100), GETDATE(), 112),3,4),1,0", ErpName, CardNumber);
  517. CmdExecuteNonQuery(sql, cmd, "插入VoucherHistory表失败!");
  518. }
  519. sql = string.Format(@"DECLARE @Code nvarchar(100)
  520. SELECT @Code = '00000' + CAST(cNumber AS NVARCHAR(50)) FROM {0}.dbo.VoucherHistory
  521. WHERE cSeed = SUBSTRING(CONVERT(varchar(100), GETDATE(), 112),3,4) AND CardNumber = '{1}'
  522. SET @Code = SUBSTRING(CONVERT(varchar(100), GETDATE(), 112),3,4)+RIGHT(@Code,4)
  523. select @Code", ErpName, CardNumber);
  524. int cCode = 0;
  525. cmd.CommandText = sql;
  526. DataTable dtCode = SQlReturnData(sql, cmd);
  527. if (dtCode != null && dtCode.Rows.Count > 0)
  528. {
  529. cCode = int.Parse(dtCode.Rows[0][0].ToString());
  530. }
  531. else
  532. {
  533. throw new Exception("获取单据号失败!");
  534. }
  535. #region
  536. //sql = string.Format("select cCode from " + TableName + " where cCode='{0}'", (PreStr + cCode).ToString());
  537. //cmd.CommandText = sql;
  538. //DataTable dtCodeCheck = SQlReturnData(sql, cmd);
  539. //if (dtCodeCheck != null && dtCodeCheck.Rows.Count > 0)
  540. //{
  541. // throw new Exception("获取单据号重复,保存失败!");
  542. //}
  543. #endregion
  544. return cCode;
  545. }
  546. public static int GetVouchCode(string ErpName, string CardNumber, string TableName, SqlCommand cmd)
  547. {
  548. string sql = "";
  549. sql = string.Format("select * from {0}.dbo.VoucherHistory where CardNumber = '{1}'", ErpName, CardNumber);
  550. DataTable dt = SQlReturnData(sql, cmd);
  551. if (dt != null && dt.Rows.Count > 0)
  552. {
  553. sql = string.Format(@"UPDATE {0}.dbo.VoucherHistory SET cNumber = cNumber+1
  554. WHERE CardNumber = '{1}'", ErpName, CardNumber);
  555. CmdExecuteNonQuery(sql, cmd, "更新VoucherHistory表失败!");
  556. }
  557. else
  558. {
  559. sql = string.Format(@"INSERT INTO {0}.dbo.VoucherHistory
  560. SELECT '{1}',NULL,'','',null,1,0", ErpName, CardNumber);
  561. CmdExecuteNonQuery(sql, cmd, "插入VoucherHistory表失败!");
  562. }
  563. sql = string.Format(@"DECLARE @Code nvarchar(100)
  564. SELECT @Code = CAST(cNumber AS NVARCHAR(50)) FROM {0}.dbo.VoucherHistory
  565. WHERE CardNumber = '{1}'
  566. SET @Code = RIGHT(@Code,10)
  567. select @Code", ErpName, CardNumber);
  568. int cCode = 0;
  569. cmd.CommandText = sql;
  570. DataTable dtCode = SQlReturnData(sql, cmd);
  571. if (dtCode != null && dtCode.Rows.Count > 0)
  572. {
  573. cCode = int.Parse(dtCode.Rows[0][0].ToString());
  574. }
  575. else
  576. {
  577. throw new Exception("获取单据号失败!");
  578. }
  579. return cCode;
  580. }
  581. public static string GetPreVouchCode(string ErpName, string CardNumber, string PreStr, SqlCommand cmd)
  582. {
  583. string cCode = "";
  584. string sql = string.Format("SELECT * FROM {0}.dbo.VoucherHistory WHERE CardNumber = '{1}' ", ErpName, CardNumber);
  585. DataTable dt = SQlReturnData(sql, cmd);
  586. if (dt != null && dt.Rows.Count > 0)
  587. {
  588. sql = string.Format(@"UPDATE {0}.dbo.VoucherHistory SET cNumber = CAST((CAST(cNumber AS INT) + 1) AS VARCHAR(30)) WHERE CardNumber = '{1}' ", ErpName, CardNumber);
  589. CmdExecuteNonQuery(sql, cmd, "更新VoucherHistory表失败!");
  590. }
  591. else
  592. {
  593. sql = string.Format(@"INSERT INTO {0}.dbo.VoucherHistory SELECT '{1}', NULL, NULL, NULL, NULL, 1, 0 ", ErpName, CardNumber);
  594. CmdExecuteNonQuery(sql, cmd, "插入VoucherHistory表失败!");
  595. }
  596. sql = string.Format(@"
  597. DECLARE @Code NVARCHAR(100)
  598. SELECT @Code = '0000000' + CAST(cNumber AS NVARCHAR(50)) FROM {0}.dbo.VoucherHistory WHERE CardNumber = '{1}'
  599. SET @Code = '{2}' + RIGHT(@Code, 3)
  600. SELECT @Code ", ErpName, CardNumber, PreStr);
  601. cmd.CommandText = sql;
  602. DataTable dtCode = SQlReturnData(sql, cmd);
  603. if (dtCode != null && dtCode.Rows.Count > 0)
  604. {
  605. cCode = dtCode.Rows[0][0].ToString();
  606. }
  607. else
  608. {
  609. throw new Exception("获取单据号失败!");
  610. }
  611. return cCode;
  612. }
  613. public static string GetRdVouchCode(string ErpName, string CardNumber, SqlCommand cmd)
  614. {
  615. string cCode = "";
  616. string sql = string.Format("SELECT * FROM {0}.dbo.VoucherHistory WHERE CardNumber = '{1}' ", ErpName, CardNumber);
  617. DataTable dt = SQlReturnData(sql, cmd);
  618. if (dt != null && dt.Rows.Count > 0)
  619. {
  620. sql = string.Format(@"UPDATE {0}.dbo.VoucherHistory SET cNumber = CAST((CAST(cNumber AS INT) + 1) AS VARCHAR(30)) WHERE CardNumber = '{1}' ", ErpName, CardNumber);
  621. CmdExecuteNonQuery(sql, cmd, "更新VoucherHistory表失败!");
  622. }
  623. else
  624. {
  625. sql = string.Format(@"INSERT INTO {0}.dbo.VoucherHistory SELECT '{1}', NULL, NULL, NULL, NULL, 1, 0 ", ErpName, CardNumber);
  626. CmdExecuteNonQuery(sql, cmd, "插入VoucherHistory表失败!");
  627. }
  628. sql = string.Format(@"
  629. DECLARE @Code NVARCHAR(100)
  630. SELECT @Code = CAST(cNumber AS NVARCHAR(50)) FROM {0}.dbo.VoucherHistory WHERE CardNumber = '{1}'
  631. SET @Code = @Code
  632. SELECT @Code ", ErpName, CardNumber);
  633. cmd.CommandText = sql;
  634. DataTable dtCode = SQlReturnData(sql, cmd);
  635. if (dtCode != null && dtCode.Rows.Count > 0)
  636. {
  637. cCode = dtCode.Rows[0][0].ToString();
  638. }
  639. else
  640. {
  641. throw new Exception("获取单据号失败!");
  642. }
  643. return cCode;
  644. }
  645. ///// <summary>
  646. ///// 获取用户的姓名与部门
  647. ///// </summary>
  648. ///// <param name="cPer_Num">用户编号</param>
  649. ///// <param name="cmd"></param>
  650. ///// <returns></returns>
  651. //public static UserInfo GetPersonInfo(string cPer_Num, SqlCommand cmd)
  652. //{
  653. // UserInfo person = new UserInfo();
  654. // string sql = @"exec sp_refreshview ua_user ;
  655. // SELECT a.cUser_Id,a.cUser_Name,b.cDepCode FROM ua_user a
  656. // LEFT JOIN dbo.Department b ON a.cDept=b.cDepName
  657. // WHERE cUser_Id ='" + cPer_Num + "'";
  658. // cmd.CommandText = sql;
  659. // DataTable dt = SQlReturnData(sql, cmd);
  660. // if (dt != null && dt.Rows.Count > 0)
  661. // {
  662. // person.DepCode = dt.Rows[0]["cDepCode"].ToString();
  663. // person.UserName = dt.Rows[0]["cUser_Name"].ToString();
  664. // person.UserCode = cPer_Num;
  665. // }
  666. // return person;
  667. //}
  668. /// <summary>
  669. /// 更新现存量
  670. /// </summary>
  671. /// <param name="cmd"></param>
  672. /// <param name="cInvCode"></param>
  673. /// <param name="cWhCode"></param>
  674. /// <param name="cBatch"></param>
  675. public static void UpdateCurrentStock(SqlCommand cmd, string cInvCode, string cWhCode, string cBatch, decimal iQuantity, VouchKey key)
  676. {
  677. #region 1 取得物料的itemID
  678. string sql = @"IF NOT EXISTS(
  679. SELECT Id FROM dbo.SCM_Item WHERE
  680. cinvcode = '{0}')
  681. BEGIN
  682. INSERT INTO dbo.SCM_Item(cInvCode ,cFree1 ,cFree2 ,cFree3 ,cFree4 , cFree5 ,
  683. cFree6 ,cFree7 ,cFree8 ,cFree9 ,cFree10 ,PartId) VALUES('{0}','','','','','','','','','','',0)
  684. END
  685. SELECT Id FROM
  686. dbo.SCM_Item WHERE cinvcode = '{0}'";
  687. sql = string.Format(sql, cInvCode);
  688. cmd.CommandText = sql;
  689. DataTable dtItem = SQlReturnData(sql, cmd);
  690. if (dtItem.Rows.Count == 0)
  691. {
  692. throw new Exception("物料的ItemID取得失败");
  693. }
  694. int ItemID = int.Parse(dtItem.Rows[0]["Id"].ToString());
  695. //log.Info("取得物料的itemID" + sql);
  696. #endregion
  697. #region 2 更新失败,插入现存量
  698. sql = @"SELECT AutoID FROM dbo.CurrentStock
  699. WHERE cWhCode = @cWhCode AND cInvCode = @cInvCode
  700. AND ItemId = @ItemId";
  701. if (cBatch != null)
  702. {
  703. if (bInvBatch(cInvCode, cmd) == true)
  704. sql += " and cBatch='" + cBatch + "' ";
  705. else
  706. sql += " and cBatch='' ";
  707. }
  708. else
  709. {
  710. sql += " and cBatch='' ";
  711. }
  712. cmd.CommandText = sql;
  713. cmd.Parameters.Clear();
  714. cmd.Parameters.Add(new SqlParameter("@cWhCode", cWhCode));
  715. cmd.Parameters.Add(new SqlParameter("@cInvCode", cInvCode));
  716. cmd.Parameters.Add(new SqlParameter("@ItemId", ItemID));
  717. DataTable dtCurrentStock = SQlReturnData(sql, cmd);
  718. //log.Info("查找现存量:" + sql);
  719. if (dtCurrentStock != null && dtCurrentStock.Rows.Count > 0)
  720. {
  721. sql = @"UPDATE dbo.CurrentStock SET iQuantity = iQuantity + @iQuantity
  722. {0}
  723. WHERE cWhCode = @cWhCode AND cInvCode = @cInvCode
  724. AND ItemId = @ItemId";
  725. if (key.cBustypeUN.Contains("入库") && key.UpdateTodoQuantity == true)
  726. {
  727. sql = string.Format(sql, ",fInQuantity=isnull(fInQuantity,0)-@iQuantity");
  728. }
  729. else if (key.cBustypeUN.Contains("出库") && key.UpdateTodoQuantity == true)
  730. {
  731. sql = string.Format(sql, ",fOutQuantity=isnull(fOutQuantity,0)-@iQuantity");
  732. }
  733. else if (key.cBustypeUN == "调拨" && key.UpdateTodoQuantity == true)
  734. {
  735. sql = string.Format(sql, ", fTransOutQuantity=ISNULL(a.fTransOutQuantity,0)-ISNULL(a.iQuantity,0),fTransInQuantity=ISNULL(fTransInQuantity,0)-ISNULL(a.iQuantity,0)");
  736. }
  737. else
  738. {
  739. sql = string.Format(sql, "");
  740. }
  741. if (cBatch != null)
  742. {
  743. if (bInvBatch(cInvCode, cmd) == true)
  744. sql += " and cBatch='" + cBatch + "' ";
  745. else
  746. sql += " and cBatch='' ";
  747. }
  748. else
  749. {
  750. sql += " and cBatch='' ";
  751. }
  752. cmd.CommandText = sql;
  753. cmd.Parameters.Clear();
  754. cmd.Parameters.Add(new SqlParameter("@iQuantity", iQuantity));
  755. cmd.Parameters.Add(new SqlParameter("@cWhCode", cWhCode));
  756. cmd.Parameters.Add(new SqlParameter("@cInvCode", cInvCode));
  757. cmd.Parameters.Add(new SqlParameter("@ItemId", ItemID));
  758. CmdExecuteNonQuery(sql, cmd, "更新现存量失败!");
  759. //log.Info("现存量更新:" + sql);
  760. }
  761. else
  762. {
  763. sql = @" INSERT INTO dbo.CurrentStock
  764. (cWhCode,cInvCode,ItemId,cBatch,iSoType,iSodid,iQuantity,
  765. iNum,cFree1,fOutQuantity,fOutNum,fInQuantity,fInNum,cFree2,
  766. cFree3,bStopFlag,fTransInQuantity,fTransInNum,
  767. fTransOutQuantity,fTransOutNum,fPlanQuantity,fPlanNum,fDisableQuantity,
  768. fDisableNum,fAvaQuantity,fAvaNum,BGSPSTOP,fStopQuantity,
  769. fStopNum,ipeqty,ipenum)
  770. SELECT @cWhCode,@cInvCode,@ItemId,@cBatch,'0','',@iQuantity,
  771. '0','','0','0','0','0','',
  772. '','0','0','0','0','0','0','0','0',
  773. '0','0','0','0','0','0','0','0'";
  774. cmd.CommandText = sql;
  775. cmd.Parameters.Clear();
  776. cmd.Parameters.Add(new SqlParameter("@cWhCode", cWhCode));
  777. cmd.Parameters.Add(new SqlParameter("@cInvCode", cInvCode));
  778. cmd.Parameters.Add(new SqlParameter("@ItemId", ItemID));
  779. cmd.Parameters.Add(new SqlParameter("@iQuantity", iQuantity));
  780. if (cBatch != null)
  781. {
  782. if (bInvBatch(cInvCode, cmd) == true)
  783. cmd.Parameters.Add(new SqlParameter("@cBatch", cBatch));
  784. else
  785. cmd.Parameters.Add(new SqlParameter("@cBatch", ""));
  786. }
  787. else
  788. {
  789. cmd.Parameters.Add(new SqlParameter("@cBatch", ""));
  790. }
  791. CmdExecuteNonQuery(sql, cmd, "插入现存量失败!");
  792. //log.Info("现存量插入:" + sql);
  793. }
  794. #endregion
  795. #region 判断现存量是否足够
  796. //sql = @"IF EXISTS(SELECT AutoID FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0)
  797. // BEGIN
  798. // DECLARE @MSG NVARCHAR(100)
  799. // SELECT @MSG='ERP库存不足!AutoID:'+CAST(AutoID AS NVARCHAR(100)) FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0
  800. // RAISERROR(@MSG,16,1)
  801. // END";
  802. //cmd.CommandText = sql;
  803. //cmd.ExecuteNonQuery();
  804. #endregion
  805. //判断仓库是否记入成本
  806. sql = "SELECT bInCost FROM Warehouse WHERE cWhCode='{0}'";
  807. sql = string.Format(sql, cWhCode);
  808. cmd.CommandText = sql;
  809. DataTable dtwh = SQlReturnData(sql, cmd);
  810. if (!dtwh.Rows[0]["bInCost"].ToString().Equals("0"))
  811. {
  812. #region 3 写入记账表
  813. sql = string.Format(@" INSERT INTO [dbo].[" + key.TableName + @"]
  814. SELECT '{0}','{1}','{2}','{3}'", key.ID, key.DID, key.cVouchTypeUN, key.cBustypeUN);
  815. cmd.CommandText = sql;
  816. CmdExecuteNonQuery(sql, cmd, "采购入库单写入记账表失败!");
  817. #endregion
  818. }
  819. #region 判断现存量是否足够
  820. sql = @"IF EXISTS(SELECT AutoID FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fOutQuantity<0 and cWhCode = '{0}' AND cInvCode = '{1}')
  821. BEGIN
  822. DECLARE @MSG NVARCHAR(100)
  823. SELECT @MSG='ERP待出库数量不足AutoID'+CAST(AutoID AS NVARCHAR(100)) FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fOutQuantity<0
  824. RAISERROR(@MSG,16,1)
  825. END";
  826. sql = string.Format(sql,cWhCode,cInvCode);
  827. cmd.CommandText = sql;
  828. cmd.ExecuteNonQuery();
  829. #endregion
  830. }
  831. /// <summary>
  832. /// 更新现存量
  833. /// </summary>
  834. /// <param name="cmd"></param>
  835. /// <param name="cInvCode"></param>
  836. /// <param name="cWhCode"></param>
  837. /// <param name="cBatch"></param>
  838. 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)
  839. {
  840. string newsql = "";
  841. string newsqlvalues = "";
  842. string NewcBatch="";
  843. if (cFree1 != null && cFree1!="")
  844. {
  845. NewcBatch += " and cFree1='{1}' ";
  846. newsql += ",cFree1";
  847. newsqlvalues = ",'" + cFree1 + @"'";
  848. }
  849. if (cFree2 != null && cFree2 != "")
  850. {
  851. NewcBatch += " and cFree2='{2}' ";
  852. newsql += ",cFree2";
  853. newsqlvalues = ",'" + cFree2 + @"'";
  854. }
  855. if (cFree3 != null && cFree3 != "")
  856. {
  857. NewcBatch += " and cFree3='{3}' ";
  858. newsql += ",cFree3";
  859. newsqlvalues = ",'" + cFree3 + @"'";
  860. }
  861. if (cFree4 != null && cFree4 != "")
  862. {
  863. NewcBatch += " and cFree4='{4}' ";
  864. newsql += ",cFree4";
  865. newsqlvalues = ",'" + cFree4 + @"'";
  866. }
  867. if (cFree5 != null && cFree5 != "")
  868. {
  869. NewcBatch += " and cFree5='{5}' ";
  870. newsql += ",cFree5";
  871. newsqlvalues = ",'" + cFree5 + @"'";
  872. }
  873. if (cFree6 != null && cFree6 != "")
  874. {
  875. NewcBatch += " and cFree6='{6}' ";
  876. newsql += ",cFree6";
  877. newsqlvalues = ",'" + cFree6 + @"'";
  878. }
  879. if (cFree7 != null && cFree7 != "")
  880. {
  881. NewcBatch += " and cFree7='{7}' ";
  882. newsql += ",cFree7";
  883. newsqlvalues = ",'" + cFree7 + @"'";
  884. }
  885. if (cFree8 != null && cFree8 != "")
  886. {
  887. NewcBatch += " and cFree8='{8}' ";
  888. newsql += ",cFree8";
  889. newsqlvalues = ",'" + cFree8 + @"'";
  890. }
  891. if (cFree9 != null && cFree9 != "")
  892. {
  893. NewcBatch += " and cFree9='{9}' ";
  894. newsql += ",cFree9";
  895. newsqlvalues = ",'" + cFree9 + @"'";
  896. }
  897. if (cFree10 != null && cFree10 != "")
  898. {
  899. NewcBatch += " and cFree10='{10}' ";
  900. newsql += ",cFree10";
  901. newsqlvalues = ",'" + cFree10 + @"'";
  902. }
  903. #region 1 取得物料的itemID
  904. string sql = @"IF NOT EXISTS(
  905. SELECT Id FROM dbo.SCM_Item WHERE
  906. cinvcode = '{0}' 1=1 )
  907. BEGIN
  908. INSERT INTO dbo.SCM_Item(cInvCode ,cFree1 ,cFree2 ,cFree3 ,cFree4 , cFree5 ,
  909. cFree6 ,cFree7 ,cFree8 ,cFree9 ,cFree10 ,PartId) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}',0)
  910. END
  911. SELECT Id FROM
  912. dbo.SCM_Item WHERE cinvcode = '{0}' 1=1 ";
  913. if (NewcBatch!="")
  914. sql = sql.Replace("1=1",NewcBatch);
  915. else
  916. sql = sql.Replace("1=1", "");
  917. sql = string.Format(sql, cInvCode, cFree1, cFree2, cFree3, cFree4, cFree5, cFree6, cFree7, cFree8, cFree9, cFree10);
  918. cmd.CommandText = sql;
  919. DataTable dtItem = SQlReturnData(sql, cmd);
  920. if (dtItem.Rows.Count == 0)
  921. {
  922. throw new Exception("物料的ItemID取得失败");
  923. }
  924. int ItemID = int.Parse(dtItem.Rows[0]["Id"].ToString());
  925. //log.Info("取得物料的itemID" + sql);
  926. #endregion
  927. #region 2 更新失败,插入现存量
  928. sql = @"SELECT AutoID FROM dbo.CurrentStock
  929. WHERE cWhCode = @cWhCode AND cInvCode = @cInvCode
  930. AND ItemId = @ItemId";
  931. if (cBatch != null)
  932. {
  933. if (bInvBatch(cInvCode, cmd) == true)
  934. sql += " and cBatch='" + cBatch + "' ";
  935. else
  936. sql += " and cBatch='' ";
  937. }
  938. else
  939. sql += " and cBatch='' ";
  940. if (cFree1 != null && cFree1 != "")
  941. sql += " and cFree1='{1}' ";
  942. if (cFree2 != null && cFree2 != "")
  943. sql += " and cFree2='{2}' ";
  944. if (cFree3 != null && cFree3 != "")
  945. sql += " and cFree3='{3}' ";
  946. if (cFree4 != null && cFree4 != "")
  947. sql += " and cFree4='{4}' ";
  948. if (cFree5 != null && cFree5 != "")
  949. sql += " and cFree5='{5}' ";
  950. if (cFree6 != null && cFree6 != "")
  951. sql += " and cFree6='{6}' ";
  952. if (cFree7 != null && cFree7 != "")
  953. sql += " and cFree7='{7}' ";
  954. if (cFree8 != null && cFree8 != "")
  955. sql += " and cFree8='{8}' ";
  956. if (cFree9 != null && cFree9 != "")
  957. sql += " and cFree9='{9}' ";
  958. if (cFree10 != null && cFree10 != "")
  959. sql += " and cFree10='{10}' ";
  960. sql = string.Format(sql, cInvCode, cFree1, cFree2, cFree3, cFree4, cFree5, cFree6, cFree7, cFree8, cFree9, cFree10);
  961. cmd.CommandText = sql;
  962. cmd.Parameters.Clear();
  963. cmd.Parameters.Add(new SqlParameter("@cWhCode", cWhCode));
  964. cmd.Parameters.Add(new SqlParameter("@cInvCode", cInvCode));
  965. cmd.Parameters.Add(new SqlParameter("@ItemId", ItemID));
  966. DataTable dtCurrentStock = SQlReturnData(sql, cmd);
  967. //log.Info("查找现存量:" + sql);
  968. if (dtCurrentStock != null && dtCurrentStock.Rows.Count > 0)
  969. {
  970. sql = @"UPDATE dbo.CurrentStock SET iQuantity = iQuantity + @iQuantity
  971. {0}
  972. WHERE cWhCode = @cWhCode AND cInvCode = @cInvCode
  973. AND ItemId = @ItemId";
  974. if (key.cBustypeUN.Contains("入库") && key.UpdateTodoQuantity == true)
  975. {
  976. sql = string.Format(sql, ",fInQuantity=isnull(fInQuantity,0)-@iQuantity");
  977. }
  978. else if (key.cBustypeUN.Contains("出库") && key.UpdateTodoQuantity == true)
  979. {
  980. sql = string.Format(sql, ",fOutQuantity=isnull(fOutQuantity,0)-@iQuantity");
  981. }
  982. else if (key.cBustypeUN == "调拨" && key.UpdateTodoQuantity == true)
  983. {
  984. sql = string.Format(sql, ", fTransOutQuantity=ISNULL(a.fTransOutQuantity,0)-ISNULL(a.iQuantity,0),fTransInQuantity=ISNULL(fTransInQuantity,0)-ISNULL(a.iQuantity,0)");
  985. }
  986. else
  987. {
  988. sql = string.Format(sql, "");
  989. }
  990. if (cBatch != null)
  991. {
  992. if (bInvBatch(cInvCode, cmd) == true)
  993. sql += " and cBatch='" + cBatch + "' ";
  994. else
  995. sql += " and cBatch='' ";
  996. }
  997. else
  998. {
  999. sql += " and cBatch='' ";
  1000. }
  1001. if (cFree1 != null && cFree1 != "")
  1002. sql += " and cFree1='{1}' ";
  1003. if (cFree2 != null && cFree2 != "")
  1004. sql += " and cFree2='{2}' ";
  1005. if (cFree3 != null && cFree3 != "")
  1006. sql += " and cFree3='{3}' ";
  1007. if (cFree4 != null && cFree4 != "")
  1008. sql += " and cFree4='{4}' ";
  1009. if (cFree5 != null && cFree5 != "")
  1010. sql += " and cFree5='{5}' ";
  1011. if (cFree6 != null && cFree6 != "")
  1012. sql += " and cFree6='{6}' ";
  1013. if (cFree7 != null && cFree7 != "")
  1014. sql += " and cFree7='{7}' ";
  1015. if (cFree8 != null && cFree8 != "")
  1016. sql += " and cFree8='{8}' ";
  1017. if (cFree9 != null && cFree9 != "")
  1018. sql += " and cFree9='{9}' ";
  1019. if (cFree10 != null && cFree10 != "")
  1020. sql += " and cFree10='{10}' ";
  1021. sql = string.Format(sql, cInvCode, cFree1, cFree2, cFree3, cFree4, cFree5, cFree6, cFree7, cFree8, cFree9, cFree10);
  1022. cmd.CommandText = sql;
  1023. cmd.Parameters.Clear();
  1024. cmd.Parameters.Add(new SqlParameter("@iQuantity", iQuantity));
  1025. cmd.Parameters.Add(new SqlParameter("@cWhCode", cWhCode));
  1026. cmd.Parameters.Add(new SqlParameter("@cInvCode", cInvCode));
  1027. cmd.Parameters.Add(new SqlParameter("@ItemId", ItemID));
  1028. CmdExecuteNonQuery(sql, cmd, "更新现存量失败!");
  1029. //log.Info("现存量更新:" + sql);
  1030. }
  1031. else
  1032. {
  1033. sql = @" INSERT INTO dbo.CurrentStock
  1034. (cWhCode,cInvCode,ItemId,cBatch,iSoType,iSodid,iQuantity,
  1035. iNum,cFree1,fOutQuantity,fOutNum,fInQuantity,fInNum,
  1036. bStopFlag,fTransInQuantity,fTransInNum,
  1037. fTransOutQuantity,fTransOutNum,fPlanQuantity,fPlanNum,fDisableQuantity,
  1038. fDisableNum,fAvaQuantity,fAvaNum,BGSPSTOP,fStopQuantity,
  1039. fStopNum,ipeqty,ipenum,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10)
  1040. SELECT @cWhCode,@cInvCode,@ItemId,@cBatch,'0','',@iQuantity,
  1041. '0','','0','0','0','0',
  1042. '0','0','0','0','0','0','0','0',
  1043. '0','0','0','0','0','0','0','0',@cFree1,@cFree2,@cFree3,@cFree4,@cFree5,@cFree6,@cFree7,@cFree8,@cFree9,@cFree10 ";
  1044. if (newsql!="")
  1045. sql = sql.Replace("1=1", newsql);
  1046. else
  1047. sql = sql.Replace("1=1", "");
  1048. if (newsqlvalues != "")
  1049. sql = sql.Replace("2=2", newsqlvalues);
  1050. else
  1051. sql = sql.Replace("2=2", "");
  1052. cmd.CommandText = sql;
  1053. cmd.Parameters.Clear();
  1054. cmd.Parameters.Add(new SqlParameter("@cWhCode", cWhCode));
  1055. cmd.Parameters.Add(new SqlParameter("@cInvCode", cInvCode));
  1056. cmd.Parameters.Add(new SqlParameter("@ItemId", ItemID));
  1057. cmd.Parameters.Add(new SqlParameter("@iQuantity", iQuantity));
  1058. cmd.Parameters.Add(new SqlParameter("@cFree1", cFree1));
  1059. cmd.Parameters.Add(new SqlParameter("@cFree2", cFree2));
  1060. cmd.Parameters.Add(new SqlParameter("@cFree3", cFree3));
  1061. cmd.Parameters.Add(new SqlParameter("@cFree4", cFree4));
  1062. cmd.Parameters.Add(new SqlParameter("@cFree5", cFree5));
  1063. cmd.Parameters.Add(new SqlParameter("@cFree6", cFree6));
  1064. cmd.Parameters.Add(new SqlParameter("@cFree7", cFree7));
  1065. cmd.Parameters.Add(new SqlParameter("@cFree8", cFree8));
  1066. cmd.Parameters.Add(new SqlParameter("@cFree9", cFree9));
  1067. cmd.Parameters.Add(new SqlParameter("@cFree10", cFree10));
  1068. if (cBatch != null)
  1069. {
  1070. if (bInvBatch(cInvCode, cmd) == true)
  1071. cmd.Parameters.Add(new SqlParameter("@cBatch", cBatch));
  1072. else
  1073. cmd.Parameters.Add(new SqlParameter("@cBatch", ""));
  1074. }
  1075. else
  1076. {
  1077. cmd.Parameters.Add(new SqlParameter("@cBatch", ""));
  1078. }
  1079. CmdExecuteNonQuery(sql, cmd, "插入现存量失败!");
  1080. //log.Info("现存量插入:" + sql);
  1081. }
  1082. #endregion
  1083. #region 判断现存量是否足够
  1084. //sql = @"IF EXISTS(SELECT AutoID FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0)
  1085. // BEGIN
  1086. // DECLARE @MSG NVARCHAR(100)
  1087. // SELECT @MSG='ERP库存不足!AutoID:'+CAST(AutoID AS NVARCHAR(100)) FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0
  1088. // RAISERROR(@MSG,16,1)
  1089. // END";
  1090. //cmd.CommandText = sql;
  1091. //cmd.ExecuteNonQuery();
  1092. #endregion
  1093. //判断仓库是否记入成本
  1094. sql = "SELECT bInCost FROM Warehouse WHERE cWhCode='{0}'";
  1095. sql = string.Format(sql, cWhCode);
  1096. cmd.CommandText = sql;
  1097. DataTable dtwh = SQlReturnData(sql, cmd);
  1098. if (!dtwh.Rows[0]["bInCost"].ToString().Equals("0"))
  1099. {
  1100. #region 3 写入记账表
  1101. sql = string.Format(@" INSERT INTO [dbo].[" + key.TableName + @"]
  1102. SELECT '{0}','{1}','{2}','{3}'", key.ID, key.DID, key.cVouchTypeUN, key.cBustypeUN);
  1103. cmd.CommandText = sql;
  1104. CmdExecuteNonQuery(sql, cmd, "采购入库单写入记账表失败!");
  1105. #endregion
  1106. }
  1107. #region 判断现存量是否足够
  1108. sql = @"IF EXISTS(SELECT AutoID FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fOutQuantity<0 and cWhCode = '{0}' AND cInvCode = '{1}')
  1109. BEGIN
  1110. DECLARE @MSG NVARCHAR(100)
  1111. SELECT @MSG='ERP待出库数量不足AutoID'+CAST(AutoID AS NVARCHAR(100)) FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fOutQuantity<0
  1112. RAISERROR(@MSG,16,1)
  1113. END";
  1114. sql = string.Format(sql, cWhCode, cInvCode);
  1115. cmd.CommandText = sql;
  1116. cmd.ExecuteNonQuery();
  1117. #endregion
  1118. }
  1119. /// <summary>
  1120. /// 判断是否启用批次管理
  1121. /// </summary>
  1122. /// <param name="cInvCode"></param>
  1123. /// <returns></returns>
  1124. public static bool bInvBatch(string cInvCode, SqlCommand cmd)
  1125. {
  1126. try
  1127. {
  1128. bool flag = false;
  1129. string sql = "SELECT bInvBatch FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
  1130. DataTable dt = SQlReturnData(sql, cmd);
  1131. if (dt != null && dt.Rows.Count > 0)
  1132. {
  1133. if (Convert.ToBoolean(dt.Rows[0][0]) == true)
  1134. {
  1135. flag = true;
  1136. }
  1137. else
  1138. {
  1139. flag = false;
  1140. }
  1141. }
  1142. return flag;
  1143. }
  1144. catch (Exception ex)
  1145. {
  1146. throw new Exception(ex.Message);
  1147. }
  1148. }
  1149. /// <summary>
  1150. /// 判断是否启自由项管理
  1151. /// </summary>
  1152. /// <param name="cInvCode"></param>
  1153. /// <returns></returns>
  1154. public static bool bFree1(string cInvCode, SqlCommand cmd)
  1155. {
  1156. try
  1157. {
  1158. bool flag = false;
  1159. string sql = "SELECT bFree1 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
  1160. DataTable dt = SQlReturnData(sql, cmd);
  1161. if (dt != null && dt.Rows.Count > 0)
  1162. {
  1163. if (Convert.ToBoolean(dt.Rows[0][0]) == true)
  1164. {
  1165. flag = true;
  1166. }
  1167. else
  1168. {
  1169. flag = false;
  1170. }
  1171. }
  1172. return flag;
  1173. }
  1174. catch (Exception ex)
  1175. {
  1176. throw new Exception(ex.Message);
  1177. }
  1178. }
  1179. public static bool bFree2(string cInvCode, SqlCommand cmd)
  1180. {
  1181. try
  1182. {
  1183. bool flag = false;
  1184. string sql = "SELECT bFree2 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
  1185. DataTable dt = SQlReturnData(sql, cmd);
  1186. if (dt != null && dt.Rows.Count > 0)
  1187. {
  1188. if (Convert.ToBoolean(dt.Rows[0][0]) == true)
  1189. {
  1190. flag = true;
  1191. }
  1192. else
  1193. {
  1194. flag = false;
  1195. }
  1196. }
  1197. return flag;
  1198. }
  1199. catch (Exception ex)
  1200. {
  1201. throw new Exception(ex.Message);
  1202. }
  1203. }
  1204. public static bool bFree3(string cInvCode, SqlCommand cmd)
  1205. {
  1206. try
  1207. {
  1208. bool flag = false;
  1209. string sql = "SELECT bFree3 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
  1210. DataTable dt = SQlReturnData(sql, cmd);
  1211. if (dt != null && dt.Rows.Count > 0)
  1212. {
  1213. if (Convert.ToBoolean(dt.Rows[0][0]) == true)
  1214. {
  1215. flag = true;
  1216. }
  1217. else
  1218. {
  1219. flag = false;
  1220. }
  1221. }
  1222. return flag;
  1223. }
  1224. catch (Exception ex)
  1225. {
  1226. throw new Exception(ex.Message);
  1227. }
  1228. }
  1229. public static bool bFree4(string cInvCode, SqlCommand cmd)
  1230. {
  1231. try
  1232. {
  1233. bool flag = false;
  1234. string sql = "SELECT bFree4 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
  1235. DataTable dt = SQlReturnData(sql, cmd);
  1236. if (dt != null && dt.Rows.Count > 0)
  1237. {
  1238. if (Convert.ToBoolean(dt.Rows[0][0]) == true)
  1239. {
  1240. flag = true;
  1241. }
  1242. else
  1243. {
  1244. flag = false;
  1245. }
  1246. }
  1247. return flag;
  1248. }
  1249. catch (Exception ex)
  1250. {
  1251. throw new Exception(ex.Message);
  1252. }
  1253. }
  1254. public static bool bFree5(string cInvCode, SqlCommand cmd)
  1255. {
  1256. try
  1257. {
  1258. bool flag = false;
  1259. string sql = "SELECT bFree5 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
  1260. DataTable dt = SQlReturnData(sql, cmd);
  1261. if (dt != null && dt.Rows.Count > 0)
  1262. {
  1263. if (Convert.ToBoolean(dt.Rows[0][0]) == true)
  1264. {
  1265. flag = true;
  1266. }
  1267. else
  1268. {
  1269. flag = false;
  1270. }
  1271. }
  1272. return flag;
  1273. }
  1274. catch (Exception ex)
  1275. {
  1276. throw new Exception(ex.Message);
  1277. }
  1278. }
  1279. public static bool bFree6(string cInvCode, SqlCommand cmd)
  1280. {
  1281. try
  1282. {
  1283. bool flag = false;
  1284. string sql = "SELECT bFree6 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
  1285. DataTable dt = SQlReturnData(sql, cmd);
  1286. if (dt != null && dt.Rows.Count > 0)
  1287. {
  1288. if (Convert.ToBoolean(dt.Rows[0][0]) == true)
  1289. {
  1290. flag = true;
  1291. }
  1292. else
  1293. {
  1294. flag = false;
  1295. }
  1296. }
  1297. return flag;
  1298. }
  1299. catch (Exception ex)
  1300. {
  1301. throw new Exception(ex.Message);
  1302. }
  1303. }
  1304. public static bool bFree7(string cInvCode, SqlCommand cmd)
  1305. {
  1306. try
  1307. {
  1308. bool flag = false;
  1309. string sql = "SELECT bFree7 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
  1310. DataTable dt = SQlReturnData(sql, cmd);
  1311. if (dt != null && dt.Rows.Count > 0)
  1312. {
  1313. if (Convert.ToBoolean(dt.Rows[0][0]) == true)
  1314. {
  1315. flag = true;
  1316. }
  1317. else
  1318. {
  1319. flag = false;
  1320. }
  1321. }
  1322. return flag;
  1323. }
  1324. catch (Exception ex)
  1325. {
  1326. throw new Exception(ex.Message);
  1327. }
  1328. }
  1329. public static bool bFree8(string cInvCode, SqlCommand cmd)
  1330. {
  1331. try
  1332. {
  1333. bool flag = false;
  1334. string sql = "SELECT bFree8 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
  1335. DataTable dt = SQlReturnData(sql, cmd);
  1336. if (dt != null && dt.Rows.Count > 0)
  1337. {
  1338. if (Convert.ToBoolean(dt.Rows[0][0]) == true)
  1339. {
  1340. flag = true;
  1341. }
  1342. else
  1343. {
  1344. flag = false;
  1345. }
  1346. }
  1347. return flag;
  1348. }
  1349. catch (Exception ex)
  1350. {
  1351. throw new Exception(ex.Message);
  1352. }
  1353. }
  1354. public static DataTable bFree(string cInvCode, SqlCommand cmd)
  1355. {
  1356. try
  1357. {
  1358. string sql = "SELECT bFree1, bFree2, bFree3, bFree4, bFree5, bFree6, bFree7, bFree8, bFree9, bFree10 FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
  1359. DataTable dt = SQlReturnData(sql, cmd);
  1360. return dt;
  1361. }
  1362. catch (Exception ex)
  1363. {
  1364. throw new Exception(ex.Message);
  1365. }
  1366. }
  1367. /// <summary>
  1368. /// 判断是否启用保质期管理
  1369. /// </summary>
  1370. /// <param name="cInvCode"></param>
  1371. /// <returns></returns>
  1372. public static bool bInvQuality(string cInvCode, SqlCommand cmd)
  1373. {
  1374. try
  1375. {
  1376. bool flag = false;
  1377. string sql = "SELECT bInvQuality FROM dbo.Inventory WHERE cInvCode='" + cInvCode + "'";
  1378. DataTable dt = SQlReturnData(sql, cmd);
  1379. if (dt != null && dt.Rows.Count > 0)
  1380. {
  1381. if (Convert.ToBoolean(dt.Rows[0][0]) == true)
  1382. {
  1383. flag = true;
  1384. }
  1385. else
  1386. {
  1387. flag = false;
  1388. }
  1389. }
  1390. return flag;
  1391. }
  1392. catch (Exception ex)
  1393. {
  1394. throw new Exception(ex.Message);
  1395. }
  1396. }
  1397. /// <summary>
  1398. /// 判断是否记账
  1399. /// </summary>
  1400. /// <param name="cInvCode"></param>
  1401. /// <returns></returns>
  1402. public static bool bInCost(string cWhCode, SqlCommand cmd)
  1403. {
  1404. try
  1405. {
  1406. bool flag = false;
  1407. string sql = "SELECT bInCost FROM Warehouse WHERE cWhCode ='" + cWhCode + "'";
  1408. DataTable dt = SQlReturnData(sql, cmd);
  1409. if (dt != null && dt.Rows.Count > 0)
  1410. {
  1411. if (Convert.ToBoolean(dt.Rows[0][0]) == true)
  1412. {
  1413. flag = true;
  1414. }
  1415. else
  1416. {
  1417. flag = false;
  1418. }
  1419. }
  1420. return flag;
  1421. }
  1422. catch (Exception ex)
  1423. {
  1424. throw new Exception(ex.Message);
  1425. }
  1426. }
  1427. /// <summary>
  1428. /// Convert a List{T} to a DataTable.
  1429. /// </summary>
  1430. public static DataTable ToDataTable<T>(List<T> items)
  1431. {
  1432. var tb = new DataTable(typeof(T).Name);
  1433. PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
  1434. foreach (PropertyInfo prop in props)
  1435. {
  1436. Type t = GetCoreType(prop.PropertyType);
  1437. tb.Columns.Add(prop.Name, t);
  1438. }
  1439. foreach (T item in items)
  1440. {
  1441. var values = new object[props.Length];
  1442. for (int i = 0; i < props.Length; i++)
  1443. {
  1444. values[i] = props[i].GetValue(item, null);
  1445. }
  1446. tb.Rows.Add(values);
  1447. }
  1448. return tb;
  1449. }
  1450. /// <summary>
  1451. /// Determine of specified type is nullable
  1452. /// </summary>
  1453. public static bool IsNullable(Type t)
  1454. {
  1455. return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
  1456. }
  1457. /// <summary>
  1458. /// Return underlying type if type is Nullable otherwise return the type
  1459. /// </summary>
  1460. public static Type GetCoreType(Type t)
  1461. {
  1462. if (t != null && IsNullable(t))
  1463. {
  1464. if (!t.IsValueType)
  1465. {
  1466. return t;
  1467. }
  1468. else
  1469. {
  1470. return Nullable.GetUnderlyingType(t);
  1471. }
  1472. }
  1473. else
  1474. {
  1475. return t;
  1476. }
  1477. }
  1478. #region 原
  1479. 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)
  1480. {
  1481. DataTable dtNew = dt.Clone();
  1482. 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] };
  1483. foreach (DataRow row in dt.Rows)
  1484. {
  1485. if (string.IsNullOrEmpty(cBatch))
  1486. {
  1487. cBatch = "";
  1488. }
  1489. if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
  1490. {
  1491. row[cBatch] = "";
  1492. }
  1493. 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() });
  1494. if (srow == null)
  1495. {
  1496. dtNew.Rows.Add(row.ItemArray);
  1497. }
  1498. else
  1499. {
  1500. srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
  1501. }
  1502. }
  1503. return dtNew;
  1504. }
  1505. public static DataTable MergeDataTable(DataTable dt, string AuotID, string cBatch, string iQuantity, string cInvCode, SqlCommand cmd)
  1506. {
  1507. DataTable dtNew = dt.Clone();
  1508. dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[AuotID], dtNew.Columns[cBatch] };
  1509. foreach (DataRow row in dt.Rows)
  1510. {
  1511. if (string.IsNullOrEmpty(cBatch))
  1512. {
  1513. cBatch = "";
  1514. }
  1515. if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
  1516. {
  1517. row[cBatch] = "";
  1518. }
  1519. DataRow srow = dtNew.Rows.Find(new object[] { row[AuotID].ToString(), row[cBatch].ToString() });
  1520. if (srow == null)
  1521. {
  1522. dtNew.Rows.Add(row.ItemArray);
  1523. }
  1524. else
  1525. {
  1526. srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
  1527. }
  1528. }
  1529. return dtNew;
  1530. }
  1531. 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)
  1532. {
  1533. DataTable dtNew = dt.Clone();
  1534. 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] };
  1535. foreach (DataRow row in dt.Rows)
  1536. {
  1537. if (string.IsNullOrEmpty(cBatch))
  1538. {
  1539. cBatch = "";
  1540. }
  1541. if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
  1542. {
  1543. row[cBatch] = "";
  1544. }
  1545. 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() });
  1546. if (srow == null)
  1547. {
  1548. dtNew.Rows.Add(row.ItemArray);
  1549. }
  1550. else
  1551. {
  1552. srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
  1553. }
  1554. }
  1555. return dtNew;
  1556. }
  1557. public static DataTable MergeDataTableQC(DataTable dt, string AuotID, string cBatch, string iQuantity, string iNGQuantity, string cInvCode, SqlCommand cmd)
  1558. {
  1559. DataTable dtNew = dt.Clone();
  1560. dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[AuotID], dtNew.Columns[cBatch] };
  1561. foreach (DataRow row in dt.Rows)
  1562. {
  1563. if (string.IsNullOrEmpty(cBatch))
  1564. {
  1565. cBatch = "";
  1566. }
  1567. if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
  1568. {
  1569. row[cBatch] = "";
  1570. }
  1571. DataRow srow = dtNew.Rows.Find(new object[] { row[AuotID].ToString(), row[cBatch].ToString() });
  1572. if (srow == null)
  1573. {
  1574. dtNew.Rows.Add(row.ItemArray);
  1575. }
  1576. else
  1577. {
  1578. srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
  1579. srow[iNGQuantity] = decimal.Parse(srow[iNGQuantity].ToString()) + decimal.Parse(row[iNGQuantity].ToString());
  1580. }
  1581. }
  1582. return dtNew;
  1583. }
  1584. 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)
  1585. {
  1586. DataTable dtNew = dt.Clone();
  1587. 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] };
  1588. foreach (DataRow row in dt.Rows)
  1589. {
  1590. if (string.IsNullOrEmpty(cBatch))
  1591. {
  1592. cBatch = "";
  1593. }
  1594. if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
  1595. {
  1596. row[cBatch] = "";
  1597. }
  1598. 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() });
  1599. if (srow == null)
  1600. {
  1601. dtNew.Rows.Add(row.ItemArray);
  1602. }
  1603. else
  1604. {
  1605. srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
  1606. }
  1607. }
  1608. return dtNew;
  1609. }
  1610. 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)
  1611. {
  1612. DataTable dtNew = dt.Clone();
  1613. 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] };
  1614. foreach (DataRow row in dt.Rows)
  1615. {
  1616. if (string.IsNullOrEmpty(cBatch))
  1617. {
  1618. cBatch = "";
  1619. }
  1620. if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
  1621. {
  1622. row[cBatch] = "";
  1623. }
  1624. 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() });
  1625. if (srow == null)
  1626. {
  1627. dtNew.Rows.Add(row.ItemArray);
  1628. }
  1629. else
  1630. {
  1631. srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
  1632. }
  1633. }
  1634. return dtNew;
  1635. }
  1636. #endregion
  1637. #region 现
  1638. public static DataTable MergeDataTableX(DataTable dt, string AuotID, string cBatch, string iQuantity, string cInvCode, string iNum, SqlCommand cmd)
  1639. {
  1640. DataTable dtNew = dt.Clone();
  1641. dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[cInvCode], dtNew.Columns[cBatch] };
  1642. foreach (DataRow row in dt.Rows)
  1643. {
  1644. if (string.IsNullOrEmpty(cBatch))
  1645. {
  1646. cBatch = "";
  1647. }
  1648. if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
  1649. {
  1650. row[cBatch] = "";
  1651. }
  1652. DataRow srow = dtNew.Rows.Find(new object[] { row[cInvCode].ToString(), row[cBatch].ToString() });
  1653. if (srow == null)
  1654. {
  1655. dtNew.Rows.Add(row.ItemArray);
  1656. }
  1657. else
  1658. {
  1659. srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
  1660. srow[iNum] = decimal.Parse(srow[iNum].ToString()) + decimal.Parse(row[iNum].ToString());
  1661. }
  1662. }
  1663. return dtNew;
  1664. }
  1665. public static DataTable MergeDataTable(DataTable dt, string AuotID, string cBatch, string iQuantity, string cInvCode, string iNum, SqlCommand cmd)
  1666. {
  1667. DataTable dtNew = dt.Clone();
  1668. //dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[AuotID], dtNew.Columns[cInvCode], dtNew.Columns[cBatch] };
  1669. dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[AuotID], dtNew.Columns[cBatch] };//原
  1670. foreach (DataRow row in dt.Rows)
  1671. {
  1672. if (string.IsNullOrEmpty(cBatch))
  1673. {
  1674. cBatch = "";
  1675. }
  1676. if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
  1677. {
  1678. row[cBatch] = "";
  1679. }
  1680. DataRow srow = dtNew.Rows.Find(new object[] { row[AuotID].ToString(), row[cBatch].ToString() });
  1681. //DataRow srow = dtNew.Rows.Find(new object[] { row[AuotID].ToString(), dtNew.Columns[cInvCode], row[cBatch].ToString() });
  1682. if (srow == null)
  1683. {
  1684. dtNew.Rows.Add(row.ItemArray);
  1685. }
  1686. else
  1687. {
  1688. srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
  1689. srow[iNum] = decimal.Parse(srow[iNum].ToString()) + decimal.Parse(row[iNum].ToString());
  1690. }
  1691. }
  1692. return dtNew;
  1693. }
  1694. public static DataTable MergeRd09(DataTable dt, string cBatch, string iQuantity, string cInvCode, string iNum, SqlCommand cmd)
  1695. {
  1696. DataTable dtNew = dt.Clone();
  1697. dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[cInvCode], dtNew.Columns[cBatch] };
  1698. foreach (DataRow row in dt.Rows)
  1699. {
  1700. if (string.IsNullOrEmpty(cBatch))
  1701. {
  1702. cBatch = "";
  1703. }
  1704. if (DBHelper.bInvBatch(row[cInvCode].ToString(), cmd) == false)
  1705. {
  1706. row[cBatch] = "";
  1707. }
  1708. DataRow srow = dtNew.Rows.Find(new object[] { row[cInvCode].ToString(), row[cBatch].ToString() });
  1709. if (srow == null)
  1710. {
  1711. dtNew.Rows.Add(row.ItemArray);
  1712. }
  1713. else
  1714. {
  1715. srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
  1716. srow[iNum] = decimal.Parse(srow[iNum].ToString()) + decimal.Parse(row[iNum].ToString());
  1717. }
  1718. }
  1719. return dtNew;
  1720. }
  1721. #endregion
  1722. public static IList<T> ConvertTo<T>(DataTable table)
  1723. {
  1724. if (table == null)
  1725. {
  1726. return null;
  1727. }
  1728. List<DataRow> rows = new List<DataRow>();
  1729. foreach (DataRow row in table.Rows)
  1730. {
  1731. rows.Add(row);
  1732. }
  1733. return ConvertTo<T>(rows);
  1734. }
  1735. public static IList<T> ConvertTo<T>(IList<DataRow> rows)
  1736. {
  1737. IList<T> list = null;
  1738. if (rows != null)
  1739. {
  1740. list = new List<T>();
  1741. foreach (DataRow row in rows)
  1742. {
  1743. T item = CreateItem<T>(row);
  1744. list.Add(item);
  1745. }
  1746. }
  1747. return list;
  1748. }
  1749. public static T CreateItem<T>(DataRow row)
  1750. {
  1751. T obj = default(T);
  1752. if (row != null)
  1753. {
  1754. obj = Activator.CreateInstance<T>();
  1755. foreach (DataColumn column in row.Table.Columns)
  1756. {
  1757. PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
  1758. try
  1759. {
  1760. object value = row[column.ColumnName];
  1761. prop.SetValue(obj, value, null);
  1762. }
  1763. catch
  1764. { //You can log something here
  1765. //throw;
  1766. }
  1767. }
  1768. }
  1769. return obj;
  1770. }
  1771. public static DataTable MergeDataTable(DataTable dt, string AuotID, string iQuantity, string cBatch)
  1772. {
  1773. DataTable dtNew = dt.Clone();
  1774. dtNew.PrimaryKey = new DataColumn[] { dtNew.Columns[AuotID] };
  1775. foreach (DataRow row in dt.Rows)
  1776. {
  1777. DataRow srow = dtNew.Rows.Find(new object[] { row[AuotID].ToString() });
  1778. if (srow == null)
  1779. {
  1780. dtNew.Rows.Add(row.ItemArray);
  1781. }
  1782. else
  1783. {
  1784. srow[iQuantity] = decimal.Parse(srow[iQuantity].ToString()) + decimal.Parse(row[iQuantity].ToString());
  1785. }
  1786. }
  1787. return dtNew;
  1788. }
  1789. #region 返回默认的出入库类别
  1790. /// <summary>
  1791. /// 返回默认的出入库类别
  1792. /// </summary>
  1793. /// <returns></returns>
  1794. public static string returnDefaultRdType(string VTID, string BTChName, SqlCommand cmd)
  1795. {
  1796. string sql = @"select VouchRdContrapose.cVRGUID,cVTChName,cBTChName,cVRRCode,R.cRdName,cVRSCode,S.cRdName
  1797. from VouchRdContrapose with(nolock)
  1798. left join vouchTypeDic with(nolock) on VouchRdContrapose.cVBTID=VouchTypeDic.cVBTID
  1799. left join Rd_Style as R with(nolock) On cVRRCode=R.cRdCode and R.bRDFlag=1
  1800. left join Rd_Style as S with(nolock) ON cVRSCode=S.cRdCode and S.bRDFlag=0
  1801. where 1=1 And (cVTID = N'{0}') And (cBTChName = N'{1}') order by cSerial ";
  1802. sql = string.Format(sql, VTID, BTChName);
  1803. DataTable dt = SQlReturnData(sql, cmd);
  1804. if (dt.Rows.Count == 0)
  1805. {
  1806. throw new Exception("倒冲材料出库单的出库类别取得失败");
  1807. }
  1808. return dt.Rows[0]["cVRSCode"].ToString();
  1809. }
  1810. #endregion
  1811. 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)
  1812. {
  1813. string sql = "";
  1814. if (DBHelper.bInvBatch(cInvCode, cmd) == true)
  1815. sql += " and cBatch='" + cBatch + "' ";
  1816. else
  1817. sql += " and cBatch='' ";
  1818. if (DBHelper.bFree1(cInvCode, cmd) == true)
  1819. sql += " and cFree1='" + cFree1 + "' ";
  1820. else
  1821. sql += " and cFree1='' ";
  1822. if (DBHelper.bFree2(cInvCode, cmd) == true)
  1823. sql += " and cFree2='" + cFree2 + "' ";
  1824. else
  1825. sql += " and cFree2='' ";
  1826. if (DBHelper.bFree3(cInvCode, cmd) == true)
  1827. sql += " and cFree3='" + cFree3 + "' ";
  1828. else
  1829. sql += " and cFree3='' ";
  1830. if (DBHelper.bFree4(cInvCode, cmd) == true)
  1831. sql += " and cFree4='" + cFree4 + "' ";
  1832. else
  1833. sql += " and cFree4='' ";
  1834. if (DBHelper.bFree5(cInvCode, cmd) == true)
  1835. sql += " and cFree5='" + cFree5 + "' ";
  1836. else
  1837. sql += " and cFree5='' ";
  1838. if (DBHelper.bFree6(cInvCode, cmd) == true)
  1839. sql += " and cFree6='" + cFree6 + "' ";
  1840. else
  1841. sql += " and cFree6='' ";
  1842. if (DBHelper.bFree7(cInvCode, cmd) == true)
  1843. sql += " and cFree7='" + cFree7 + "' ";
  1844. else
  1845. sql += " and cFree7='' ";
  1846. if (DBHelper.bFree8(cInvCode, cmd) == true)
  1847. sql += " and cFree8='" + cFree8 + "' ";
  1848. else
  1849. sql += " and cFree8='' ";
  1850. return sql;
  1851. }
  1852. 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)
  1853. {
  1854. bool bFree1 = false;
  1855. bool bFree2 = false;
  1856. bool bFree3 = false;
  1857. bool bFree4 = false;
  1858. bool bFree5 = false;
  1859. bool bFree6 = false;
  1860. bool bFree7 = false;
  1861. bool bFree8 = false;
  1862. #region 自由项管控
  1863. DataTable SubdtFree = DBHelper.bFree(cInvCode, cmd);
  1864. if (SubdtFree.Rows.Count > 0 && SubdtFree != null)
  1865. {
  1866. bFree1 = Convert.ToBoolean(SubdtFree.Rows[0]["bFree1"]);
  1867. bFree2 = Convert.ToBoolean(SubdtFree.Rows[0]["bFree2"]);
  1868. bFree3 = Convert.ToBoolean(SubdtFree.Rows[0]["bFree3"]);
  1869. bFree4 = Convert.ToBoolean(SubdtFree.Rows[0]["bFree4"]);
  1870. bFree5 = Convert.ToBoolean(SubdtFree.Rows[0]["bFree5"]);
  1871. bFree6 = Convert.ToBoolean(SubdtFree.Rows[0]["bFree6"]);
  1872. bFree7 = Convert.ToBoolean(SubdtFree.Rows[0]["bFree7"]);
  1873. bFree8 = Convert.ToBoolean(SubdtFree.Rows[0]["bFree8"]);
  1874. }
  1875. else
  1876. {
  1877. throw new Exception("存货编码:" + cInvCode + "不存在");
  1878. }
  1879. #endregion
  1880. string sql = "";
  1881. if (DBHelper.bInvBatch(cInvCode, cmd) == true)
  1882. sql += " and cBatch='" + cBatch + "' ";
  1883. else
  1884. sql += " and cBatch='' ";
  1885. if (bFree1)
  1886. {
  1887. sql += " and cFree1='" + cFree1 + "' ";
  1888. }
  1889. else
  1890. {
  1891. sql += " and cFree1='' ";
  1892. }
  1893. if (bFree2)
  1894. {
  1895. sql += " and cFree2='" + cFree2 + "' ";
  1896. }
  1897. else
  1898. {
  1899. sql += " and cFree2='' ";
  1900. }
  1901. if (bFree3)
  1902. {
  1903. sql += " and cFree3='" + cFree3 + "' ";
  1904. }
  1905. else
  1906. {
  1907. sql += " and cFree3='' ";
  1908. }
  1909. if (bFree4)
  1910. {
  1911. sql += " and cFree4='" + cFree4 + "' ";
  1912. }
  1913. else
  1914. {
  1915. sql += " and cFree4='' ";
  1916. }
  1917. if (bFree5)
  1918. {
  1919. sql += " and cFree5='" + cFree5 + "' ";
  1920. }
  1921. else
  1922. {
  1923. sql += " and cFree5='' ";
  1924. }
  1925. if (bFree6)
  1926. {
  1927. sql += " and cFree6='" + cFree6 + "' ";
  1928. }
  1929. else
  1930. {
  1931. sql += " and cFree6='' ";
  1932. }
  1933. if (bFree7)
  1934. {
  1935. sql += " and cFree7='" + cFree7 + "' ";
  1936. }
  1937. else
  1938. {
  1939. sql += " and cFree7='' ";
  1940. }
  1941. if (bFree8)
  1942. {
  1943. sql += " and cFree8='" + cFree8 + "' ";
  1944. }
  1945. else
  1946. {
  1947. sql += " and cFree8='' ";
  1948. }
  1949. return sql;
  1950. }
  1951. /// <summary>
  1952. /// 方法一:获取编号 返回Dictionary字典,调用该方法用Dictionary字典接收,只需要遍历Dictionary即可得到响应的值
  1953. /// </summary>
  1954. /// <param name="workPointCode"></param>
  1955. /// <param name="tbName"></param>
  1956. /// <param name="colName"></param>
  1957. /// <param name="Pre"></param>
  1958. /// <param name="numLen"></param>
  1959. /// <returns>返回Dictionary字典</returns>
  1960. public static Dictionary<string, int> GetAllCode(string cAcc_Id, string cVouchType, string iAmount)
  1961. {
  1962. string iFatherId = string.Empty, iChildId = string.Empty;
  1963. Dictionary<string, int> dic = new Dictionary<string, int>();
  1964. try
  1965. {
  1966. SqlConnection conn = new SqlConnection(ERPConnString);
  1967. SqlCommand cmd = new SqlCommand("sp_GetIDWithoutRemote", conn);
  1968. cmd.CommandType = CommandType.StoredProcedure;
  1969. cmd.Parameters.AddWithValue("@cAcc_Id", cAcc_Id);  //给输入参数赋值
  1970. cmd.Parameters.AddWithValue("@cVouchType", cVouchType);  //给输入参数赋值
  1971. cmd.Parameters.AddWithValue("@iAmount", iAmount);  //给输入参数赋值
  1972. //cmd.Parameters.AddWithValue("@iFatherId", iFatherId);  //给输入参数赋值
  1973. //cmd.Parameters.AddWithValue("@iChildId", iChildId);  //给输入参数赋值
  1974. SqlParameter parOutput = cmd.Parameters.Add("@iFatherId", SqlDbType.NVarChar, 50);  //定义输出参数
  1975. cmd.Parameters["@iFatherId"].Direction = ParameterDirection.Output;
  1976. SqlParameter parOutputs = cmd.Parameters.Add("@iChildId", SqlDbType.NVarChar, 50);  //定义输出参数
  1977. cmd.Parameters["@iChildId"].Direction = ParameterDirection.Output;
  1978. SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int);
  1979. parReturn.Direction = ParameterDirection.ReturnValue;   //参数类型为ReturnValue
  1980. cmd.Parameters.Add(parReturn);
  1981. conn.Open();
  1982. cmd.ExecuteNonQuery();
  1983. iFatherId = cmd.Parameters["@iFatherId"].Value.ToString();
  1984. iChildId = cmd.Parameters["@iChildId"].Value.ToString();
  1985. if (!string.IsNullOrWhiteSpace(iFatherId))//判断iFatherId是否为空,不为空的话将值放入dictionary字典中,否则int.Parse()会抛出异常
  1986. {
  1987. dic.Add("iFatherId", int.Parse(iFatherId));
  1988. dic.Add("iChildId", int.Parse(iChildId));
  1989. }
  1990. }
  1991. catch (System.Exception ex)
  1992. {
  1993. throw ex;
  1994. }
  1995. return dic;
  1996. }
  1997. /// <summary>
  1998. /// 方法二 使用输出参数值
  1999. /// </summary>
  2000. /// <param name="cAcc_Id"></param>
  2001. /// <param name="cVouchType"></param>
  2002. /// <param name="iAmount"></param>
  2003. /// <returns></returns>
  2004. public static void GetAllCode(string cAcc_Id, string cVouchType, string iAmount, out int iFatherId, out int iChildId)
  2005. {
  2006. try
  2007. {
  2008. iFatherId = 0; iChildId = 0;
  2009. SqlConnection conn = new SqlConnection(ERPConnString);
  2010. SqlCommand cmd = new SqlCommand("sp_GetIDWithoutRemote", conn);
  2011. cmd.CommandType = CommandType.StoredProcedure;
  2012. cmd.Parameters.AddWithValue("@cAcc_Id", cAcc_Id);  //给输入参数赋值
  2013. cmd.Parameters.AddWithValue("@cVouchType", cVouchType);  //给输入参数赋值
  2014. cmd.Parameters.AddWithValue("@iAmount", iAmount);  //给输入参数赋值
  2015. //cmd.Parameters.AddWithValue("@iFatherId", iFatherId);  //给输入参数赋值
  2016. //cmd.Parameters.AddWithValue("@iChildId", iChildId);  //给输入参数赋值
  2017. SqlParameter parOutput = cmd.Parameters.Add("@iFatherId", SqlDbType.NVarChar, 50);  //定义输出参数
  2018. cmd.Parameters["@iFatherId"].Direction = ParameterDirection.Output;
  2019. SqlParameter parOutputs = cmd.Parameters.Add("@iChildId", SqlDbType.NVarChar, 50);  //定义输出参数
  2020. cmd.Parameters["@iChildId"].Direction = ParameterDirection.Output;
  2021. //SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int);
  2022. //parReturn.Direction = ParameterDirection.ReturnValue;   //参数类型为ReturnValue
  2023. //cmd.Parameters.Add(parReturn);
  2024. conn.Open();
  2025. cmd.ExecuteNonQuery();
  2026. string _iFatherId = cmd.Parameters["@iFatherId"].Value.ToString();
  2027. string _iChildId = cmd.Parameters["@iChildId"].Value.ToString();
  2028. if (!string.IsNullOrWhiteSpace(_iFatherId))
  2029. {
  2030. iFatherId = int.Parse(_iFatherId);
  2031. }
  2032. if (!string.IsNullOrWhiteSpace(_iChildId))
  2033. {
  2034. iChildId = int.Parse(_iChildId);
  2035. }
  2036. }
  2037. catch (System.Exception ex)
  2038. {
  2039. throw ex;
  2040. }
  2041. }
  2042. /// <summary>
  2043. /// 方法二 使用输出参数值
  2044. /// </summary>
  2045. /// <param name="cAcc_Id"></param>
  2046. /// <param name="cVouchType"></param>
  2047. /// <param name="iAmount"></param>
  2048. /// <returns></returns>
  2049. public static string GetAllRDCode(string CardNumber, string dDate, string UserCode)
  2050. {
  2051. string iBaseCodeLen = string.Empty; string cVouchCodeBase = string.Empty;
  2052. Dictionary<string, int> dic = new Dictionary<string, int>();
  2053. try
  2054. {
  2055. SqlConnection conn = new SqlConnection(ERPConnString);
  2056. SqlCommand cmd = new SqlCommand("ICS_VoucherNumber", conn);
  2057. cmd.CommandType = CommandType.StoredProcedure;
  2058. cmd.Parameters.AddWithValue("@CardNumber", CardNumber);  //给输入参数赋值
  2059. cmd.Parameters.AddWithValue("@dDate", dDate);  //给输入参数赋值
  2060. cmd.Parameters.AddWithValue("@UserCode", UserCode);  //给输入参数赋值
  2061. SqlParameter parOutput = cmd.Parameters.Add("@number", SqlDbType.NVarChar, 50);  //定义输出参数
  2062. parOutput.Direction = ParameterDirection.Output;
  2063. //SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int);
  2064. //parReturn.Direction = ParameterDirection.ReturnValue;   //参数类型为ReturnValue
  2065. //cmd.Parameters.Add(parReturn);
  2066. conn.Open();
  2067. cmd.ExecuteNonQuery();
  2068. return parOutput.Value.ToString();
  2069. //iBaseCodeLen = cmd.Parameters["@iBaseCodeLen"].Value.ToString();
  2070. // cVouchCodeBase = cmd.Parameters["@cVouchCodeBase"].Value.ToString();
  2071. //UserCode= cmd.Parameters["@cVouchCodePreFix"].Value.ToString();
  2072. ////if (!string.IsNullOrWhiteSpace(iBaseCodeLen))//判断iFatherId是否为空,不为空的话将值放入dictionary字典中,否则int.Parse()会抛出异常
  2073. ////{
  2074. //// dic.Add("iBaseCodeLen", int.Parse(iBaseCodeLen));
  2075. ////}
  2076. ////else
  2077. ////{
  2078. //// dic.Add("cVouchCodeBase", int.Parse(cVouchCodeBase));
  2079. // UserCode= UserCode + (cVouchCodeBase.ToString().PadLeft(int.Parse(iBaseCodeLen), '0'));
  2080. ////}
  2081. }
  2082. catch (System.Exception ex)
  2083. {
  2084. throw ex;
  2085. }
  2086. //return UserCode;
  2087. }
  2088. public static string GetRDCode(string RDName,SqlCommand cmd)
  2089. {
  2090. string sql = @"select cRdCode from Rd_Style where cRdName='{0}'";
  2091. sql = string.Format(sql,RDName);
  2092. DataTable dt = SQlReturnData(sql,cmd);
  2093. return dt.Rows[0]["cRdCode"].ToString();
  2094. }
  2095. /// <summary>
  2096. /// DataSet转Json字符串,主子结构
  2097. /// 需要建立主子表关系,第一张表为主表
  2098. /// 会排除关联列
  2099. /// </summary>
  2100. /// <param name="dataSet"></param>
  2101. /// <param name="RelationName">关系名称</param>
  2102. /// <returns></returns>
  2103. public static string DataSetToJson(DataSet dataSet, string RelationName)
  2104. {
  2105. StringBuilder jsonString = new StringBuilder();
  2106. //foreach (DataTable table in dataSet.Tables)
  2107. //{
  2108. DataTable table = dataSet.Tables[0];
  2109. jsonString.Append("[");
  2110. DataRowCollection drc = table.Rows;
  2111. for (int i = 0; i < drc.Count; i++)
  2112. {
  2113. DataRow dataRow = drc[i];
  2114. jsonString.Append("{");
  2115. for (int j = 0; j < table.Columns.Count; j++)
  2116. {
  2117. string strKey = table.Columns[j].ColumnName;
  2118. if (dataSet.Relations[RelationName].ParentColumns.Select(a => a.Caption).Contains(strKey))
  2119. continue;
  2120. string strValue = dataRow[j].ToString();
  2121. Type type = table.Columns[j].DataType;
  2122. jsonString.Append("\"" + strKey + "\":");
  2123. strValue = StringFormat(strValue, type);
  2124. if (j < table.Columns.Count - 1)
  2125. {
  2126. jsonString.Append(strValue + ",");
  2127. }
  2128. else
  2129. {
  2130. jsonString.Append(strValue);
  2131. }
  2132. }
  2133. jsonString.Append(",\"" + RelationName + "\":");
  2134. DataRow[] drs = dataRow.GetChildRows(RelationName);
  2135. jsonString.Append("[");
  2136. foreach (DataRow dr in drs)
  2137. {
  2138. DataTable dt = dr.Table;
  2139. jsonString.Append("{");
  2140. for (int j = 0; j < dt.Columns.Count; j++)
  2141. {
  2142. string strKey = dt.Columns[j].ColumnName;
  2143. if (dataSet.Relations[RelationName].ChildColumns.Select(a => a.Caption).Contains(strKey))
  2144. continue;
  2145. string strValue = dr[j].ToString();
  2146. Type type = dt.Columns[j].DataType;
  2147. jsonString.Append("\"" + strKey + "\":");
  2148. strValue = StringFormat(strValue, type);
  2149. if (j < dt.Columns.Count - 1)
  2150. {
  2151. jsonString.Append(strValue + ",");
  2152. }
  2153. else
  2154. {
  2155. jsonString.Append(strValue);
  2156. }
  2157. }
  2158. jsonString.Append("},");
  2159. }
  2160. if (drs.Length > 0)
  2161. jsonString.Remove(jsonString.Length - 1, 1);
  2162. jsonString.Append("]");
  2163. jsonString.Append("},");
  2164. }
  2165. jsonString.Remove(jsonString.Length - 1, 1);
  2166. jsonString.Append("]");
  2167. //}
  2168. string res = jsonString.ToString();
  2169. return res;
  2170. }
  2171. #region 私有方法
  2172. /// <summary>
  2173. /// 过滤特殊字符
  2174. /// </summary>
  2175. /// <param name="s">字符串</param>
  2176. /// <returns>json字符串</returns>
  2177. private static string String2Json(String s)
  2178. {
  2179. StringBuilder sb = new StringBuilder();
  2180. for (int i = 0; i < s.Length; i++)
  2181. {
  2182. char c = s.ToCharArray()[i];
  2183. switch (c)
  2184. {
  2185. case '\"':
  2186. sb.Append("\\\""); break;
  2187. case '\\':
  2188. sb.Append("\\\\"); break;
  2189. case '/':
  2190. sb.Append("\\/"); break;
  2191. case '\b':
  2192. sb.Append("\\b"); break;
  2193. case '\f':
  2194. sb.Append("\\f"); break;
  2195. case '\n':
  2196. sb.Append("\\n"); break;
  2197. case '\r':
  2198. sb.Append("\\r"); break;
  2199. case '\t':
  2200. sb.Append("\\t"); break;
  2201. default:
  2202. sb.Append(c); break;
  2203. }
  2204. }
  2205. return sb.ToString();
  2206. }
  2207. /// <summary>
  2208. /// 格式化字符型、日期型、布尔型
  2209. /// </summary>
  2210. /// <param name="str"></param>
  2211. /// <param name="type"></param>
  2212. /// <returns></returns>
  2213. private static string StringFormat(string str, Type type)
  2214. {
  2215. if (type == typeof(string))
  2216. {
  2217. str = String2Json(str);
  2218. str = "\"" + str + "\"";
  2219. }
  2220. else if (type == typeof(DateTime))
  2221. {
  2222. str = "\"" + str + "\"";
  2223. }
  2224. else if (type == typeof(bool))
  2225. {
  2226. str = str.ToLower();
  2227. }
  2228. else if (type != typeof(string) && string.IsNullOrEmpty(str))
  2229. {
  2230. str = "\"" + str + "\"";
  2231. }
  2232. return str;
  2233. }
  2234. #endregion
  2235. public static DataSet SQlReturnDataSet(string SQl, SqlCommand cmd)
  2236. {
  2237. DataSet ds = new DataSet();
  2238. SqlDataAdapter dr = new System.Data.SqlClient.SqlDataAdapter();
  2239. cmd.CommandText = SQl;
  2240. dr.SelectCommand = cmd;
  2241. dr.Fill(ds);
  2242. return ds;
  2243. }
  2244. /// <summary>
  2245. /// 获取用户的姓名与部门
  2246. /// </summary>
  2247. /// <param name="cPer_Num">用户编号</param>
  2248. /// <param name="cmd"></param>
  2249. /// <returns></returns>
  2250. public static ICSUserInfo GetPersonInfo(string cPer_Num, SqlCommand cmd)
  2251. {
  2252. ICSUserInfo person = new ICSUserInfo();
  2253. string sql = @" exec sp_refreshview ua_user ;
  2254. SELECT a.cUser_Id,a.cUser_Name,b.cDepCode FROM ua_user a
  2255. LEFT JOIN dbo.Department b ON a.cDept=b.cDepName
  2256. WHERE cUser_Id ='" + cPer_Num + "'";
  2257. cmd.CommandText = sql;
  2258. DataTable dt = SQlReturnData(sql, cmd);
  2259. if (dt != null && dt.Rows.Count > 0)
  2260. {
  2261. person.DepCode = dt.Rows[0]["cDepCode"].ToString();
  2262. person.UserName = dt.Rows[0]["cUser_Name"].ToString();
  2263. person.UserCode = cPer_Num;
  2264. }
  2265. else
  2266. throw new Exception("ERP人员不存在,编码:" + cPer_Num);
  2267. return person;
  2268. }
  2269. }
  2270. }