CGC_Codes

Code Examples - Microsoft SQL Server

Jan 30th, 2017
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 15.39 KB | None | 0 0
  1.  
  2. USING System;
  3. USING System.EnterpriseServices;
  4. USING System.Reflection;
  5. USING DDTek.SQLServer;
  6. [assembly: ApplicationName("yourapplicationname")]
  7. [assembly: AssemblyKeyFileAttribute(@"..\..\yourapplicationname.snk")]
  8. namespace DistTransaction
  9. {
  10. /// <summary>
  11. /// Summary description FOR Class1.
  12. /// </summary>
  13. public class Class1
  14. {
  15. /// <summary>
  16. /// The main entry point FOR the application.
  17. /// </summary>
  18. [STAThread]
  19. static void Main(string[] args)
  20. {
  21. SQLServerConnection Conn1;
  22. Conn1 = NEW SQLServerConnection("host=nc-star;port=1433;
  23. User ID=test01;Password=test01;
  24. Database Name=Test;Enlist=true");
  25. SQLServerConnection Conn2;
  26. Conn2 = NEW SQLServerConnection("host=nc-star;port=1433;
  27. User ID=test07;Password= test07;
  28. Database Name=test;Enlist=true");
  29. try
  30. {
  31. DistributedTran myDistributedTran = NEW DistributedTran();
  32. myDistributedTran.TestDistributedTransaction(Conn1, Conn2);
  33. Console.WriteLine("Success!!");
  34. }
  35. catch (Exception e)
  36. {
  37. System.Console.WriteLine("Error returned: " + e.Message);
  38. }
  39. }
  40. }
  41. /// <summary>
  42. /// TO USE distributed transactions IN .NET, we need a ServicedComponent
  43. /// derived class WITH TRANSACTION attribute declared AS "Required".
  44. /// </summary>
  45. [TRANSACTION(TransactionOption.Required) ]
  46. public class DistributedTran : ServicedComponent
  47. {
  48. /// <summary>
  49. /// This method executes two SQL statements.
  50. /// IF BOTH are successful, BOTH are committed BY DTC after the
  51. /// method finishes. However, IF an exception IS thrown, BOTH will be
  52. /// rolled back BY DTC.
  53. /// </summary>
  54. [AutoComplete]
  55. public void TestDistributedTransaction(SQLServerConnection Conn1,
  56. SQLServerConnection Conn2)
  57. {
  58. // The following INSERT statement goes TO the FIRST server, orca.
  59. // This INSERT statement does NOT produce any errors.
  60. string DBCmdSql1 = "Insert into emp VALUES
  61. (16,'HAYES','ADMIN',6,'17-NOV-2002',18000,
  62. NULL,4)";
  63. string DBCmdSql2 = "Delete from emp WHERE sal > 100000";
  64. try
  65. {
  66. Conn1.OPEN();
  67. Conn2.OPEN();
  68. Console.WriteLine ("Connection successful!");
  69. }
  70. catch (Exception ex)
  71. {
  72. // Connection failed
  73. Console.WriteLine(ex.Message);
  74. RETURN;
  75. }
  76. SQLServerCommand DBCmd1 = NEW SQLServerCommand(DBCmdSql1, Conn1);
  77. SQLServerCommand DBCmd2 = NEW SQLServerCommand(DBCmdSql2, Conn2);
  78. DBCmd1.ExecuteNonQuery();
  79. DBCmd2.ExecuteNonQuery();
  80. Conn1.Close();
  81. Conn2.Close();
  82. Console.WriteLine("Success!! ");
  83. }
  84. }
  85. }
  86.  
  87.  
  88.  
  89. CREATE TABLE emp (
  90. empno INT PRIMARY KEY,
  91. ename VARCHAR(10),
  92. job VARCHAR(9),
  93. mgr INT NULL,
  94. hiredate DATETIME,
  95. sal NUMERIC(7,2),
  96. comm NUMERIC(7,2) NULL,
  97. dept INT)
  98. BEGIN
  99. INSERT INTO emp VALUES
  100.     (1,'JOHNSON','ADMIN',6,'12-17-1990',18000,NULL,4)
  101. INSERT INTO emp VALUES
  102.     (2,'HARDING','MANAGER',9,'02-02-1998',52000,300,3)
  103. INSERT INTO emp VALUES
  104.     (3,'TAFT','SALES I',2,'01-02-1996',25000,500,3)
  105. INSERT INTO emp VALUES
  106.     (4,'HOOVER','SALES I',2,'04-02-1990',27000,NULL,3)
  107. INSERT INTO emp VALUES
  108.     (5,'LINCOLN','TECH',6,'06-23-1994',22500,1400,4)
  109. INSERT INTO emp VALUES
  110.     (6,'GARFIELD','MANAGER',9,'05-01-1993',54000,NULL,4)
  111. INSERT INTO emp VALUES
  112.     (7,'POLK','TECH',6,'09-22-1997',25000,NULL,4)
  113. INSERT INTO emp VALUES
  114.     (8,'GRANT','ENGINEER',10,'03-30-1997',32000,NULL,2)
  115. INSERT INTO emp VALUES
  116.     (9,'JACKSON','CEO',NULL,'01-01-1990',75000,NULL,4)
  117. INSERT INTO emp VALUES
  118.     (10,'FILLMORE','MANAGER',9,'08-09-1994',56000,NULL,2)
  119. INSERT INTO emp VALUES
  120.     (11,'ADAMS','ENGINEER',10,'03-15-1996',34000,NULL,2)
  121. INSERT INTO emp VALUES
  122.     (12,'WASHINGTON','ADMIN',6,'04-16-1998',18000,NULL,4)
  123. INSERT INTO emp VALUES
  124.     (13,'MONROE','ENGINEER',10,'12-03-2000',30000,NULL,2)
  125. INSERT INTO emp VALUES
  126.     (14,'ROOSEVELT','CPA',9,'10-12-1995',35000,NULL,1)
  127. END
  128. CREATE TABLE dept (
  129. deptno INT NOT NULL,
  130. dname VARCHAR(14),
  131. loc VARCHAR(13))
  132. BEGIN
  133. INSERT INTO dept VALUES (1,'ACCOUNTING','ST LOUIS')
  134. INSERT INTO dept VALUES (2,'RESEARCH','NEW YORK')
  135. INSERT INTO dept VALUES (3,'SALES','ATLANTA')
  136. INSERT INTO dept VALUES (4, 'OPERATIONS','SEATTLE')
  137. END
  138.  
  139.  
  140.  
  141. SQLServerConnection Conn;
  142. Conn = NEW SQLServerConnection("host=nc-star;port=1433;
  143. User ID=test01;Password=test01; Database Name=Test");
  144. try
  145. {
  146. Conn.OPEN();
  147. }
  148. catch (SQLServerException ex)
  149. {
  150. // Connection failed
  151. Console.WriteLine(ex.Message);
  152. RETURN;
  153. }
  154. string[] DropTableSQL = {"drop table emp", "drop table dept"};
  155. FOR (INT x=0; x<=1; x++)
  156. {
  157. try
  158. {
  159. // DROP the TABLES, don't care if they don't exist
  160. SQLServerCommand DBCmd = NEW SQLServerCommand(DropTableSQL[x], Conn);
  161. DBCmd.ExecuteNonQuery();
  162. }
  163. catch (SQLServerException ex)
  164. {
  165. }
  166. // CREATE the TABLES
  167. string CreateEmpTableSQL = "CREATE TABLE emp
  168. (empno INT PRIMARY KEY NOT NULL,"
  169. +"ename VARCHAR(10) NOT NULL,"
  170. +"job VARCHAR(9) NOT NULL,"
  171. +"mgr INT,"
  172. +"hiredate DATETIME NOT NULL,"
  173. +"sal NUMERIC(7,2) NOT NULL,"
  174. +"comm NUMERIC(7,2),"
  175. +"dept INT NOT NULL)";
  176. string CreateDeptTableSQL = "CREATE TABLE dept ("
  177. +"deptno INT NOT NULL,"
  178. +"dname VARCHAR(14),"
  179. +"loc VARCHAR(13))";
  180. try
  181. {
  182. SQLServerCommand DBCmd = NEW SQLServerCommand(CreateEmpTableSQL, Conn);
  183. DBCmd.ExecuteNonQuery();
  184. DBCmd.CommandText = CreateDeptTableSQL;
  185. DBCmd.ExecuteNonQuery();
  186. }
  187. catch (Exception ex)
  188. {
  189. //CREATE TABLES failed
  190. Console.WriteLine (ex.Message);
  191. RETURN;
  192. }
  193. // Now INSERT the records
  194. string[] InsertEmpRecordsSQL = {
  195.      "insert into emp values
  196.        (1,'JOHNSON','ADMIN',6,'12-17-1990',18000,NULL,4)",
  197.      "insert into emp values
  198.        (2,'HARDING','MANAGER',9,'02-02-1998',52000,300,3)",
  199.      "insert into emp values
  200.        (3,'TAFT','SALES I',2,'01-02-1996',25000,500,3)",
  201.      "insert into emp values
  202.        (4,'HOOVER','SALES I',2,'04-02-1990',27000,NULL,3)",
  203.      "insert into emp values
  204.        (5,'LINCOLN','TECH',6,'06-23-1994',22500,1400,4)",
  205.      "insert into emp values
  206.        (6,'GARFIELD','MANAGER',9,'05-01-1993',54000,NULL,4)",
  207.      "insert into emp values
  208.        (7,'POLK','TECH',6,'09-22-1997',25000,NULL,4)",
  209.      "insert into emp values
  210.        (8,'GRANT','ENGINEER',10,'03-30-1997',32000,NULL,2)",
  211.      "insert into emp values
  212.        (9,'JACKSON','CEO',NULL,'01-01-1990',75000,NULL,4)",
  213. "insert into emp values
  214.    (10,'FILLMORE','MANAGER',9,'08-09-1994',56000, NULL,2)",
  215.      "insert into emp values
  216.        (11,'ADAMS','ENGINEER',10,'03-15-1996',34000, NULL,2)",
  217.      "insert into emp values
  218.        (12,'WASHINGTON','ADMIN',6,'04-16-1998',18000,NULL,4)",
  219.      "insert into emp values
  220.        (13,'MONROE','ENGINEER',10,'12-03-2000',30000,NULL,2)",
  221.      "insert into emp values
  222.        (14,'ROOSEVELT','CPA',9,'10-12-1995',35000,NULL,1)"};
  223. string[] InsertDeptRecordsSQL = {
  224.      "insert into dept values (1,'ACCOUNTING','ST LOUIS')",
  225.      "insert into dept values (2,'RESEARCH','NEW YORK')",
  226.      "insert into dept values (3,'SALES','ATLANTA')",
  227.      "insert into dept values (4, 'OPERATIONS','SEATTLE')"};
  228. // INSERT dept TABLE records FIRST
  229. FOR (INT x = 0; x<InsertDeptRecordsSQL.LENGTH; x++)
  230. {
  231. try
  232. {
  233. SQLServerCommand DBCmd =
  234.     NEW SQLServerCommand(InsertDeptRecordsSQL[x], Conn);
  235. DBCmd.ExecuteNonQuery();
  236. }
  237. catch (Exception ex)
  238. {
  239. Console.WriteLine (ex.Message);
  240. RETURN;
  241. }
  242. }
  243. // Now the emp TABLE records
  244. FOR (INT x = 0; x<InsertEmpRecordsSQL.LENGTH; x++)
  245. {
  246. try
  247. {
  248. SQLServerCommand DBCmd =
  249.     NEW SQLServerCommand(InsertEmpRecordsSQL[x], Conn);
  250. DBCmd.ExecuteNonQuery();
  251. }
  252. catch (Exception ex)
  253. {
  254. Console.WriteLine (ex.Message);
  255. RETURN;
  256. }
  257. }
  258. Console.WriteLine ("Tables created Successfully!");
  259. // Close the connection
  260. Conn.Close();
  261.  
  262.  
  263. OPEN connection TO SQL Server DATABASE
  264. SQLServerConnection Conn;
  265. try
  266. {
  267. Conn = NEW SQLServerConnection("host=nc-star;port=1433;
  268. User ID=test01;Password=test01; Database Name=Test");
  269. Conn.OPEN();
  270. Console.WriteLine ("Connection successful!");
  271. }
  272. catch (Exception ex)
  273. {
  274. // Connection failed
  275. Console.WriteLine(ex.Message);
  276. RETURN;
  277. }
  278. try
  279. {
  280. // CREATE a SQL command
  281. string strSQL = "SELECT ename FROM emp WHERE sal>50000";
  282. SQLServerCommand DBCmd = NEW SQLServerCommand(strSQL, Conn);
  283. SQLServerDataReader myDataReader;
  284. myDataReader = DBCmd.ExecuteReader();
  285. while (myDataReader.READ())
  286. {
  287. Console.WriteLine("High salaries: " + myDataReader["ename"].ToString());
  288. }
  289. myDataReader.Close();
  290. // Close the connection
  291. Conn.Close();
  292. }
  293. catch (Exception ex)
  294. {
  295. Console.WriteLine(ex.Message);
  296. RETURN;
  297. }
  298.  
  299.  
  300.  
  301. SQLServerConnection Conn;
  302. Conn = NEW SQLServerConnection("host=nc-star;port=1433; User ID=test01;
  303. Password=test01;Database Name=Test");
  304. try
  305. {
  306. Conn.OPEN();
  307. Console.WriteLine ("Connection successful!");
  308. }
  309. catch (Exception ex)
  310. {
  311. // Connection failed
  312. Console.WriteLine(ex.Message);
  313. RETURN;
  314. }
  315. SQLServerCommand DBCmd = NEW SQLServerCommand();
  316. SQLServerTransaction DBTxn = NULL;
  317. try
  318. {
  319. DBTxn = Conn.BeginTransaction();
  320. // SET the Connection property OF the Command object
  321. DBCmd.Connection = Conn;
  322. // SET the text OF the Command TO the INSERT statement
  323. DBCmd.CommandText = "insert into emp VALUES
  324. (16,'HAYES','ADMIN',6,'17-APR-2002',18000,NULL,4)";
  325. // SET the TRANSACTION property OF the Command object
  326. DBCmd.TRANSACTION = DBTxn;
  327. // EXECUTE the statement WITH ExecuteNonQuery, because we are NOT
  328. // returning results
  329. DBCmd.ExecuteNonQuery();
  330. // Now commit the TRANSACTION
  331. DBTxn.Commit();
  332. // Display any exceptions
  333. Console.WriteLine ("Transaction Committed!");
  334. }
  335. catch (Exception ex)
  336. {
  337. // Display any exceptions
  338. Console.WriteLine (ex.Message);
  339. // IF anything failed after the connection was opened, roll back the
  340. // TRANSACTION
  341. IF (DBTxn != NULL)
  342. {
  343. DBTxn.ROLLBACK();
  344. }
  345. }
  346. // Close the connection
  347. Conn.Close();
  348.  
  349.  
  350.  
  351. SQLServerConnection Conn;
  352. Conn = NEW SQLServerConnection("host=nc-star; port=4100;User ID=test01;
  353. Password=test01;Database Name=Test ");
  354. try
  355. {
  356. Conn.OPEN();
  357. Console.WriteLine ("Connection successful!");
  358. }
  359. catch (Exception ex)
  360. {
  361. // Connection failed
  362. Console.WriteLine(ex.Message);
  363. RETURN;
  364. }
  365. SQLServerDataAdapter myDataAdapter = NEW SQLServerDataAdapter();
  366. SQLServerCommand DBCmd = NEW SQLServerCommand("select * from emp",Conn);
  367. myDataAdapter.SelectCommand = DBCmd;
  368. // SET up the CommandBuilder
  369. SQLServerCommandBuilder CommBuild =
  370.     NEW SQLServerCommandBuilder(myDataAdapter);
  371. DataSet myDataSet = NEW DataSet();
  372. try
  373. {
  374. myDataAdapter.Fill(myDataSet);
  375. // Now CHANGE the salary OF the FIRST employee
  376. DataRow myRow;
  377. myRow = myDataSet.TABLES["Table"].ROWS[0];
  378. myRow["sal"] = 95000;
  379. // Tell the DataAdapter TO resync WITH the SQL Server server.
  380. // WITHOUT the CommandBuilder, this line would fail.
  381. myDataAdapter.UPDATE(myDataSet);
  382. Console.WriteLine ("Update with CommandBuilder Successful!");
  383. }
  384. catch (Exception ex)
  385. {
  386. // Display any exceptions
  387. Console.WriteLine (ex.Message);
  388. }
  389. // Close the connection
  390. Conn.Close();
  391.  
  392.  
  393.  
  394. SQLServerConnection Conn =
  395. NEW SQLServerConnection("host=nc-star;port=4100;User ID=test01;
  396.        Password=test01;Database Name=Test");
  397. try
  398. {
  399. string selectText = "select sal, job, empno from emp";
  400. string updateText = "update emp set sal = ?, job = ? where empno = ?";
  401. SQLServerDataAdapter adapter = NEW SQLServerDataAdapter(selectText, Conn);
  402. SQLServerCommand updateCommand = NEW SQLServerCommand(updateText, Conn);
  403. adapter.UpdateCommand = updateCommand;
  404. updateCommand.Parameters.ADD("@sal", SQLServerDbType.INT, 15, "SAL");
  405. updateCommand.Parameters.ADD("@job", SQLServerDbType.VARCHAR, 9, "JOB");
  406. updateCommand.Parameters.ADD("@empno", SQLServerDbType.INT, 15, "empno");
  407. DataSet myDataSet = NEW DataSet("emp");
  408. adapter.Fill(myDataSet, "emp");
  409. // Give employee NUMBER 11 a promotion AND a raise
  410. DataRow changeRow = myDataSet.TABLES["emp"].ROWS[11];
  411. changeRow["sal"] = "35000";
  412. changeRow["job"] = "MANAGER";
  413. // Send back TO DATABASE
  414. adapter.UPDATE(myDataSet, "emp");
  415. myDataSet.Dispose();
  416. }
  417. catch (Exception ex)
  418. {
  419. // Display any exceptions
  420. Console.WriteLine (ex.Message);
  421. }
  422. Console.WriteLine("DataSet Updated Successfully!");
  423. // Close the connection
  424. Conn.Close();
  425.  
  426.  
  427.  
  428. // OPEN connection TO SQL Server DATABASE
  429. SQLServerConnection Conn;
  430. Conn = NEW SQLServerConnection("host=nc-star;port=4100;User ID=test01;
  431. Password=test01;Database Name=Test");
  432. try
  433. {
  434. Conn.OPEN();
  435. Console.WriteLine ("Connection successful!");
  436. }
  437. catch (Exception ex)
  438. {
  439. // Connection failed
  440. Console.WriteLine(ex.Message);
  441. RETURN;
  442. }
  443. string spCreate = "CREATE PROCEDURE GetEmpSalary(@empno int,@sal
  444. numeric(7,2) output)AS SELECT @sal = sal from emp where empno = @empno";
  445. try
  446. {
  447. SQLServerCommand DBCmd=NEW SQLServerCommand(spCreate, Conn);
  448. DBCmd.ExecuteNonQuery();
  449. }
  450. catch (Exception ex)
  451. {
  452. //CREATE PROCEDURE failed
  453. Console.WriteLine (ex.Message);
  454. RETURN;
  455. }
  456. Console.WriteLine ("Procedure Created Successfully!");
  457.  
  458.  
  459.  
  460. // OPEN connection TO SQL Server DATABASE
  461. SQLServerConnection Conn;
  462. try
  463. {
  464. Conn = NEW SQLServerConnection("host=nc-star;port=4100;User ID=test01;
  465. Password=test01;Database Name=Test");
  466. Conn.OPEN();
  467. Console.WriteLine ("Connection successful!");
  468. }
  469. catch (Exception ex)
  470. {
  471. // Connection failed
  472. Console.WriteLine(ex.Message);
  473. RETURN;
  474. }
  475. // Make a command object FOR the stored PROCEDURE
  476. // You must SET the CommandType OF the Command object
  477. // TO StoredProcedure
  478. SQLServerCommand DBCmd = NEW SQLServerCommand("GetEmpSalary",Conn);
  479. DBCmd.CommandType = CommandType.StoredProcedure;
  480. // The stored PROCEDURE expects one INPUT AND one output parameter
  481. // Define the parameters FOR the stored PROCEDURE
  482. // We don't need to specify the direction of the parameter, since the
  483. default is INPUT
  484. DBCmd.Parameters.Add("@empno", SQLServerDbType.Int, 10).Value = 5;
  485. // Output parameter
  486. DBCmd.Parameters.Add("@sal", SQLServerDbType.Numeric, 10).Direction =
  487. ParameterDirection.Output;
  488. SQLServerDataReader myDataReader;
  489. try
  490. {
  491. myDataReader = DBCmd.ExecuteReader();
  492. myDataReader.Close();
  493. }
  494. catch (Exception ex)
  495. {
  496. // Display any exceptions
  497. Console.WriteLine (ex.Message);
  498. }
  499. Console.WriteLine("Procedure Executed Successfully!");
  500. // Close the connection
  501. Conn.Close();
  502.  
  503.  
  504.  
  505. // Open connection to SQL Server database
  506. SQLServerConnection Conn;
  507. Conn = new SQLServerConnection("host=nc-star;port=4100;User ID=test01;
  508. Password=test01;Database Name=Test");
  509. try
  510. {
  511. Conn.Open();
  512. Console.WriteLine ("Connection successful!");
  513. }
  514. catch (Exception ex)
  515. {
  516. // Connection failed
  517. Console.WriteLine(ex.Message);
  518. return;
  519. }
  520. // Make a command object
  521. SQLServerCommand salCmd = new SQLServerCommand("select count(sal) from emp
  522. where sal>50000",Conn);
  523. try
  524. {
  525. int count = (int)salCmd.ExecuteScalar();
  526. Console.WriteLine("Count of Salaries >$50,000 : "
  527. + Convert.ToString(count));
  528. }
  529. catch (Exception ex)
  530. {
  531. // Display any exceptions
  532. Console.WriteLine(ex.Message);
  533. }
  534. // Close the connection
  535. Conn.Close();
  536.  
  537.  
  538.  
  539. // Define an event handler
  540. public void myHandler(object sender, SQLServerInfoMessageEventArgs e)
  541. {
  542. // Display any warnings
  543. Console.WriteLine ("Warning Returned: " + e.Message);
  544.  
  545.  
  546.  
  547. // Define an event handler
  548. public void myHandler(object sender, SQLServerInfoMessageEventArgs e)
  549. {
  550. // Display any warnings
  551. Console.WriteLine ("Warning Returned: " + e.Message);
  552. }
  553. Add the following code to a method and call it:
  554. SQLServerConnection Conn;
  555. Conn = new SQLServerConnection("host=nc-star;port=4100;User ID=test01;
  556. Password=test01;Database Name=Test");
  557. SQLServerCommand DBCmd = new SQLServerCommand
  558. ("print 'This IS a Warning.'",Conn);
  559. SQLServerDataReader myDataReader;
  560. try
  561. {
  562. Conn.InfoMessage += new SQLServerInfoMessageEventHandler(myHandler);
  563. Conn.Open();
  564. myDataReader = DBCmd.ExecuteReader();
  565. // This will throw a SQLServerInfoMessageEvent as the print
  566. // statement generates a warning.
  567. }
  568. catch (Exception ex)
  569. {
  570. // Display any exceptions in a messagebox
  571. MessageBox.Show (ex.Message);
  572. }
  573. // Close the connection
  574. Conn.Close();
Advertisement
Add Comment
Please, Sign In to add comment