목차

MS SqlServer basic

Create Database with collation / Unicode

CREATE DATABASE MyOptionsTest  
COLLATE Korean_Wansung_CI_AS;  
GO
 
USE master;  
GO
ALTER DATABASE MyOptionsTest  
COLLATE Korean_Wansung_CI_AS;  
GO  

Table/Databases

EXEC sp_databases
GO

Table 목록 보기

EXEC sp_tables
GO
 
GO 
EXEC sp_tables 
@TABLE_NAME = '%', 
@table_owner = 'dbo', 
@table_qualifier = 'model'; 
GO
-- 원하는 테이블 검색
SELECT name
  FROM DBname.sys.tables
 WHERE name LIKE '%xxx%'
   AND is_ms_shipped = 0; -- << 불필요하면 제거

Table Description

-- 테이블 정보 보기
EXEC sp_help tablename
GO
 
SELECT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.Columns 
WHERE TABLE_NAME = 'tablename';
 
GO

EXISTS

-- 조건을 만족하는 첫번째 것에서 바로 중단하고 1 혹은 0 반환
SELECT COUNT(1)  WHERE EXISTS (SELECT * FROM books WHERE book_type='IT')

UPSERT

-- 이 방법은 SQLServer 2008 이후로는 사용하지 말라고 함.
UPDATE test SET name='john' WHERE id=3012
IF @@ROWCOUNT=0
   INSERT INTO test(name) VALUES('john');
-- TEST 가 UPDATE/INSERT 대상 테이블일 때
MERGE dbo.TEST AS T
USING (SELECT 3, 300) AS S (userSN, col1) -- update or insert 할 데이터 테이블. SELECT로 가상 테이블 만듬
ON T.userSN = S.userSN
WHEN MATCHED THEN
       UPDATE SET col1 = S.col1
WHEN NOT MATCHED BY TARGET THEN
       INSERT (userSN, col1) VALUES (S.userSN, S.col1);

Offset/Limit Paging

SELECT *
FROM Sales.SalesOrderDetail
ORDER BY SalesOrderDetailID
OFFSET 20 ROWS
FETCH NEXT 10 ROWS ONLY;
GO

DATE, TIME 컬럼 합쳐서 DATETIME 만들기

-- modifyDate : DATE, modifyTime : TIME 컬럼일 경우
CAST(modifyDate AS DATETIME) + CAST(modifyTime AS DATETIME) modifiedAt

공백제거

SELECT REPLACE(REPLACE(@str, CHAR(13), ''), CHAR(10), '')

FORMAT

SELECT FORMAT(CAST('07:35' AS TIME), N'hh\.mm');  --> returns 07.35  
SELECT FORMAT(CAST('07:35' AS TIME), N'hh\:mm');  --> returns 07:35  

String to DATETIME

-- 2019-09-20 18:51:47
DECLARE @d NVARCHAR(14)='20170920185147';
 
SELECT 
   DATETIMEFROMPARTS (LEFT(@d, 4),  SUBSTRING(@d, 5,2), SUBSTRING(@d,7 ,2), SUBSTRING(@d, 9, 2) , SUBSTRING(@d, 11, 2), RIGHT(@d, 2), 0) as "with_var",
   DATETIMEFROMPARTS (LEFT('20170920185147', 4),  SUBSTRING('20170920185147', 5,2), SUBSTRING('20170920185147',7 ,2), SUBSTRING('20170920185147', 9, 2) , SUBSTRING('20170920185147', 11, 2), RIGHT('20170920185147', 2), 0) as "with_literal",
   DATETIME2FROMPARTS (LEFT('20170920185147', 4),  SUBSTRING('20170920185147', 5,2), SUBSTRING('20170920185147',7 ,2), SUBSTRING('20170920185147', 9, 2) , SUBSTRING('20170920185147', 11, 2), RIGHT('20170920185147', 2), 0, 0) as "dt2"
;