1 / 57

3.Introduction of Transaction-SQL

3.Introduction of Transaction-SQL. 기본질의 작성과 실행 SQL Server 프로그래밍 도구 Transact-SQL 프로그래밍 언어 Transact-SQL 의 요소들 Transact-SQL 의 실행방법 질의 처리 과정 Practice. 데이터 가져오기. SELECT 사용하기 열을 명시하기 WHERE 을 이용한 특정 행을 명시하기 WHERE 을 이용한 검색. SELECT 사용하기. Select List 는 열을 명시 WHERE Clause 는 행을 명시

wilson
Download Presentation

3.Introduction of Transaction-SQL

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 3.Introduction of Transaction-SQL • 기본질의 작성과 실행 • SQL Server 프로그래밍 도구 • Transact-SQL 프로그래밍 언어 • Transact-SQL의 요소들 • Transact-SQL의 실행방법 • 질의 처리 과정 • Practice

  2. 데이터 가져오기 • SELECT 사용하기 • 열을 명시하기 • WHERE을 이용한 특정 행을 명시하기 • WHERE을 이용한 검색

  3. SELECT 사용하기 • Select List는 열을 명시 • WHERE Clause는 행을 명시 • FROM Clause는 테이블 명시 Partial Syntax SELECT [ALL | DISTINCT] <select_list> FROM {<table_source>} [,…n] WHERE <search_condition>

  4. USE northwind SELECT employeeid, lastname, firstname, title FROM employees employeeid lastname firstname title 1 Davolio Nancy Sales Representative 2 Fuller Andrew Vice President, Sales 3 Leverling Janet Sales Representative 4 Peacock Margaret Sales Representative 5 Buchanan Steven Sales Manager 6 Suyama Michael Sales Representative 7 King Robert Sales Representative 8 Callahan Laura Inside Sales Coordinator 9 Dodsworth Anne Sales Representative 특정 열을 명시하기

  5. USE northwind SELECT employeeid, lastname, firstname, title FROM employees WHERE employeeid = 5 employeeid lastname firstname title 5 Buchanan Steven Sales Manager WHERE을 이용한 특정행을 명시하기

  6. WHERE을 이용한 검색 • Using Comparison Operators • Using String Comparisons • Using Logical Operators • Retrieving a Range of Values • Using a List of Values as Search Criteria • Retrieving Unknown Values

  7. 설명 탐색조건 Comparison operators =,>,<, >=, <=, and <> String Comparisons Like and Not Like Logical operators AND, OR, NOT Range of Values BETWEEN and NOT BETWEEN Lists of Values IN and NOT IN Unknown values IS NULL and IS NOT NULL

  8. USE northwind SELECT lastname, city FROM employees WHERE country = 'USA' lastname city Davolio Seattle Fuller Tacoma Leverling Kirkland Peacock Redmond Callahan Seattle Using Comparison Operators

  9. USE northwind SELECT companyname FROM customers WHERE companyname LIKE '%Restaurant%' companyname GROSELLA-Restaurante Lonesome Pine Restaurant Tortuga Restaurante Using String Comparisons

  10. Wildcard Characters(%, _, [], [^]) 를 사용한 예제 LIKE ‘BR%’ Every name beginning with the letters BR LIKE ‘%en%’ Every name containing the letters en LIKE ‘_en’ Every three-letter name ending in the letters en LIKE ‘[CK]%’ Every name beginning with the letter C or K LIKE ‘[S-V]ing’ Every four-letter name ending in the letters ing and beginning with any single letter from S to V LIKE ‘M[^c]%’ Every name beginning with the letter M that dose not have the letter c as the second letter

  11. USE northwind SELECT productid, productname, supplierid, unitpriceFROM productsWHERE(productname LIKE 'T%' OR productid = 46) AND (unitprice > 16.00) productid productname supplierid unitprice 14 Tofu 6 23.25 29 Thüringer Rostbratwurst 12 123.79 62 Tarte au sucre 29 49.3 Using Logical Operators

  12. USE northwind SELECT productname, unitprice FROM products WHERE unitprice BETWEEN 10 AND 20 productname unitprice Chai 18 Chang 19 Aniseed Syrup 10 Genen Shouyu 15.5 Pavlova 17.45 Sir Rodney’s Scones 10 . . . . . . Retrieving a Range of Values

  13. 주의사항 -SQL Server include the end values in the result set BETWEEN x AND y 는 다음과 같다. (>=x AND <= y) -BETWEEN 연산자를 날자와 함께 사용하는 것은 피해라. 왜냐하면 , 자정이 Ending date value에 대한 endpoint로써 Ending date value에 대한 데이터는 구해지지 않는다. 예) 1/1/98과 1/2/98을 between연산자를 사용해서 명시하면, 오직 1/1/98일에 대한 데이터만 명시된다. 만일, 1/1/98과 1/2/98 사이의 데이터를 얻기 위해서는 1/1/98과 1/3/98로 날짜를 명시해야 한다. -

  14. USE northwind SELECT companyname, country FROM suppliers WHERE country IN ('Japan', 'Italy') companyname country Tokyo Traders Japan Mayumi’s Japan Formaggi Fortini s.r.l. Italy Pasta Buttini s.r.l. Italy Using a List of Values as Search Criteria

  15. companyname fax Exotic Liquids NULL New Orleans Cajun Delights NULL Tokyo Traders NULL Cooperativa de Quesos ‘Las Cabras’ NULL . . . Retrieving Unknown Values USE northwind SELECT companyname, fax FROM suppliers WHERE fax IS NULL

  16. 결과값 구성하기 • Sorting Data • Eliminating Duplicates • Changing Column Names • Using Literals

  17. USE northwind SELECT productid, productname, categoryid, unitprice FROM products ORDER BY categoryid, unitprice DESC productid productname categoryid unitprice 38 Cote de Blaye 1 263.5 43 Ipoh Coffee 1 46 2 Chang 1 19 . . . 63 Vegie-spread 2 43.9 8 Northwoods Cranberry Sauce 2 40 61 Sirop d'érable 2 28.5 . . . 데이터 정렬하기

  18. 참고사항 -sort order는 SQL Server가 인스톨 될 때 결정된다. -SQL Server sorts in ascending order by default -Columns that are included in the ORDER BY clause do not have to appear in the select list -Do not use an ORDER BY clause on text or image columns

  19. country Australia Brazil Canada Denmark Finland France Germany Italy Japan Netherlands Norway Singapore Spain Sweden UK USA 중복성을 제거하기 USE northwind SELECT DISTINCT country FROM suppliers ORDER BY country If you specify a DISTINCT clause, the ORDER BY clause must include the columns listed in the result set

  20. USE northwind SELECT firstname AS First, lastname AS Last, employeeidAS 'Employee ID:' FROM employees First Last Employee ID: Nancy Davolio 1 Andrew Fuller 2 Janet Leverling 3 Margaret Peacock 4 Steven Buchanan 5 Michael Suyama 6 Robert King 7 Laura Callahan 8 Anne Dodsworth 9 칼럼이름 바꾸기

  21. -Creat more readable column names by using the AS keyword to replace default column names with aliases in the select list 참고사항 - By default, the result set displays the column names that are designated in the CREATE TABLE statement - Include single quotation marks for column names that contains blank spaces or that do not conform to SQL Server object naming conventions -You can include up to 128 characters in a column alias

  22. USE northwind SELECT firstname, lastname, 'Identification number:', employeeid FROM employees firstname lastname employeeid Nancy Davolio Identification number: 1 Andrew Fuller Identification number: 2 Janet Leverling Identification number: 3 Margaret Peacock Identification number: 4 Steven Buchanan Identification number: 5 Michael Suyama Identification number: 6 Robert King Identification number: 7 Laura Callahan Identification number: 8 Anne Dodsworth Identification number: 9 Using Literals

  23. 데이터 조작하기 • Inserting Rows (삽입) • Deleting Rows (삭제) • Updating Rows (갱신)

  24. Inserting Rows USE northwind INSERT customers (customerid, companyname, contactname, contacttitle, address, city, region, postalcode, country, phone, fax) VALUES ('PECOF', 'Pecos Coffee Company', 'Michael Dunn', 'Owner', '1900 Oak Street', 'Vancouver', 'BC', 'V3F 2K1', 'Canada', '(604) 555-3392', '(604) 555-7293')

  25. Inserting Data by Using Default Values • DEFAULT Keyword • Inserts default values for specified columns • Columns must have a default value or allow null values • DEFAULT VALUES Keyword • Inserts default values for all columns • Columns must have a default value or allow null values USE northwind INSERT shippers (companyname, phone) VALUES ('Kenya Coffee Co.', DEFAULT)

  26. Adding new data USE northwind INSERT shippers (companyname) VALUES ('Fitch & Mather') Verifying new data USE northwind SELECT * FROM shippers WHERE companyname = 'Fitch & Mather' shipperid companyname phone 37 Fitch & Mather NULL Inserting Partial Data Allows NULL Values 37

  27. Deleting Rows • DELETE Statement • Use to remove one or more rows in a table • Always include a WHERE clause • Each deleted row is logged in the transaction log • TRUNCATE TABLE Statement • Use to delete all rows in a table • SQL Server retains table structure and associated objects • Only deallocation of data pages is logged in the transaction log

  28. Updating Rows • WHERE Clause Specifies Rows to Change • SET Keyword Specifies the New Data • Input Values Must Be the Same Data Types as Columns USE northwind UPDATE products SET unitprice = (unitprice * 1.1)

  29. 성능 고려 사항 • Positive Search 조건 사용하라. • LIKE 검색 조건 사용을 피해라. • Exact Matches or Ranges 사용하라. • ORDER BY 절은 다소 느린 데이터 검색을 수행

  30. SQL Server 프로그래밍 도구 • SQL Server Query Analyzer • Color-codes syntax elements automatically • Multiple query windows • customizable views of result sets • Graphical execution plans • Execute portions of scripts • osql 유틸리티 • 커맨드 라인 유틸리티

  31. Osql utility - 운영체제에서 case-sensitive 옵션으로 바로 수행된다. - go 명령으로 SQL문을 실행시킨다. - EXIT나 QUIT 명령을 사용해서 실행을 중지한다. 옵션들 -S server_name 네트워크상의 서버의 이름을 명시한다. -U login_id 사용자 로그인 아이디 -P password 사용자의 암호 예) osql -Sinstructor833 -Usa -Ppass833

  32. Transact-SQL 프로그래밍 언어 • Entry-Level ANSI SQL-92 ISO 표준에 따른 구현 • 다양한 Entry-Level 제품과의 호환성 • 부가적인 특수 기능 포함

  33. Transact-SQL의 요소들 • 데이터 제어 언어(Data Control Language Statement) • 데이터 정의 언어(Data Definition Language Statement) • 데이터 조작 언어(Data Manipulation Language Statement) • 부가적 언어 요소(Additional Language Elements)

  34. 데이터 제어 언어 • Set or Change Permission • GRANT • DENY • REVOKE • 일반적으로 sysadmin, dbcreator, db_owner와 db_securityadmin 권한을 지닌 사람만이 실행 가능 예) This example grants the public role permission to query the Products table Grant select on Products to public

  35. 데이터 정의 언어 • 데이터 베이스 객체 정의한다. • CREATE 객체_이름 • ALTER 객체_이름 • DROP 객체_이름

  36. DDL statements define the database by creating databases, tables, and user-defined data types. You also use DDL statement to manage your database objects 예) The following script creates a table called customer in the northwind database. USE northwind Create Table customer (cust_id int, company varchar(40), contact varchar(30), phone char(12))

  37. SQL 서버 객체 이름 • Standard Identifier • 첫 글자는 알파벳으로 시작해야 한다. • 그 이외는 문자, 숫자, 심볼(,@, #)을 포함. • 심볼로 시작하는 이름은 특정 목적을 지님. • Delimited Identifier • 공백이 포함한 이름을 사용할 때 • 예약어가 이름의 부분으로 사용될 때 • 대괄호([])나 쌍따옴표(“ ”)를 사용해서 표현

  38. Identifier names starting with a symbol have special uses as follows 1. An identifier beginning with the @ symbol denotes a local variable or parameter 2. An identifier beginning with a pound sing(#) denotes a temporary table or procedure 3.An identifier beginning with a double pound sing(##) denotes a global temporary object 4.An identifier beginning with a double @ symbol denotes a system function

  39. 객체이름 명명에 대한 지침 • 가능하면 짧은 이름 • 가능하면 의미 있는 이름 사용 • 단순하고 명료한 명명방식 사용 • 객체의 종류를 구별할 수 있는 식별자 이용 • 뷰, 저장 프로시져 • 객체 이름과 사용자 이름은 유일하게 • Sales table and sales role(X)

  40. 데이터 조작 언어 • 데이터를 가지고 작업을 할때 사용한다. • SELECT • INSERT • UPDATE • DELETE

  41. 부가적 언어 요소 • 지역변수 • 연산자 • 함수 • 제어 구문 • 주석

  42. 지역 변수 • DECLARE문을 사용해서 선언된다. • SET문을 사용해서 값을 할당한다. DECLARE @vlname char(20)SET @vlname = ‘Dodsworth’ SELECT lastname, firstname, title FROM northwind..employees WHERE lastname = @vlnameGO

  43. 연산자 • 연산자 종류 • Arithmetic(+, -, *, /, %) • Comparison(=, >, <, >=,<=,<>) • String concatenation(+) • Logical(AND, OR , NOT) • 연산자 우선 순위 • (), Arithmetic, String concatenation,Comparison, Logical Operator의 순서

  44. 함 수(Fuctions) • Rowset 함수 • Aggregate 함수 • 스칼라 함수 SELECT * FROM OPENQUERY (OracleSvr, 'SELECT name, id FROM owner.titles') SELECT AVG (unitprice) FROM products SELECT DB_NAME() AS 'database'

  45. Function Examples 1.현재 사용자이름과 응용프로그램 이름 USE northwind SELECT user_name(), app_name() 2.현재 날짜 USE northwind SELECT getdate() 3.현재 날짜를 변환하기 USE northwind SELECT ‘ANSI:’, convert(varchar(30), getdate(), 102) AS style

  46. 제어 구문 • Statement Level • BEGIN … END 블록 • IF… ELSE 블록 • WHILE 구문 - CONTINUE, BREAK • Row Level • CASE 구문 • CASE expression {WHEN expression THEN result} [,…n] [ELSE result] END

  47. 제어구문 예제 USE northwind IF EXISTS (SELECT orderid FROM orders WHERE customerid =‘frank’) PRINT ‘*** Customer cannot be deleted ***’ ELSE BEGIN DELETE customers WHERE customerid = ‘frank’ PRINT ‘*** Customer deleted ***’ END

  48. 주석 • 행 단위 주석 • 블록 단위 주석 SELECT productname, (unitsinstock - unitsonorder) -- Calculates inventory, supplierIDFROM products /* ** This code retrieves all rows of the products table ** and displays the unit price, the unit price increased ** by 10 percent, and the name of the product. */ SELECT unitprice, (unitprice * 1.1), productname FROM products

  49. Transact-SQL문 실행 방법 • 동적으로 TSQL 생성하는 방법 • 배치를 이용 • 스크립트를 이용하는 방법 • Transaction를 이용하는 방법

  50. 동적으로 구문 생성하는 방법 • ‘EXECUTE’를 이용한다. • Execute ({@str_var| ‘tsql_string’} + […..])} • 실행시 변수의 값을 할당해야 할때 사용한다. • 실행 중에만 변수나 임시 테이블이 존재한다. DECLARE @dbname varchar(30), @tblname varchar(30)SET @dbname = 'northwind'SET @tblname = 'products' EXECUTE('USE ' + @dbname + ' SELECT * FROM ’+ @tblname)

More Related