Case Sensitive Check

1. Return names contain upper case 

Select id, name from A where name<>lower(name) collate SQL_Latin1_General_CP1_CS_AS

2. Return same name but diff case 

Select id, A.name, B.name from A inner join B on A.name=B.name where A.name<>B.name collate SQL_Latin1_General_CP1_CS_AS 

 

 

Cast & Convert (change data type)

Cast is compatible to both sql server and mysql, convert is designed for sql server, and it can have more styles and specially useful for datetime (check datetime part)

select cast(1.23 as int) --return 1
select convert( int,1.23) --return 1

 

 

Create a column of numbers (usually ids)

DECLARE @startnum INT=1000 --start
DECLARE @endnum INT=1020 --end 
;
WITH gen AS (
    SELECT @startnum AS num
    UNION ALL
    --change number+ i to adjust gap i
    SELECT num+3 FROM gen WHERE num+1<=@endnum 
)
SELECT * FROM gen
option (maxrecursion 10000)

num
1000
1003
1006
1009
1012
1015
1018
1021

 

Create a column of strings from one long string

;WITH Split(stpos,endpos)
        AS(
            SELECT 0 AS stpos, CHARINDEX(',','Alice,Jack,Tom') AS endpos 
            UNION ALL
            SELECT endpos+1, CHARINDEX(',','Alice,Jack,Tom',endpos+1) FROM Split WHERE endpos > 0
        )  
        --LTRIM RTRIM to get rid of white space before start or after end of str
        SELECT RTRIM(LTRIM(SUBSTRING('Alice,Jack,Tom',stpos,COALESCE(NULLIF(endpos,0),LEN('Alice,Jack,Tom')+1)-stpos))) as name into #temp
        FROM Split

name
Alice
Jack
Tom

 

 

Create a table of lots of strings in same column

SELECT * into #temp FROM (VALUES (1,'Alice'),(2,'Jack'),(3,'Tom')) AS t(id,name)

 id name
1 Alice
2 Jack
3 Tom

 

 

Create a temp table (copy a table)

 1. From a existing table, no need create table (not copy indexing or primary key)

Select id, name, 'placeholder' as sex into #temp from A

Trick to copy a table structure(cols and datatype) but not content

--0=1 to not copy any rows
Select id, name into #temp from A where 0=1 

--the above query equals to 
select id, name into #temp from #temp1
delete from #temp1

2. Create temp table (lifespan: current session, drop on close tab)

create table #tmpStudent(Id int IDENTITY(1,1) PRIMARY KEY,Name varchar(50),Age int) insert into #tmpStudent select id,name,age from #tmpStudent

3. Global temp table (##temp, can visit from other tab, drop on close tab where it is created)

4. Using table variable (lifespan: current transaction, drop after running query block)

DECLARE @temp Table ( Id int, Name varchar(20), Age int )

 

 

 Datetime 

1. Current date/datetime/UTC date, convert datetime to date only

select GETDATE()
select GETUTCDATE()
select cast(GETDATE() as date)  --date only
SELECT convert(date, GETDATE() ) --date only

2. Tomorrow/yesterday, next/last hour (simple nearby datetime)

-- add or minus is on day basis
select GETDATE()+1 --tomorrow
select GETDATE()-1 --yesterday

-- need to be 24.0 to return float
select GETDATE()+1.0/24 --next hour
select GETDATE()-1.0/24/2 --Last 30 min

3. Add/minus any period for a date (use with 4.datediff)

--result is already datetime
select DATEADD(yy,-2,'07/23/2009 13:23:44') --2 years ago
select DATEADD(mm,5, DATEADD(dd,10,GETDATE())) --5 month and 10 days later

The datepart can be ‘year’ or ‘yy’ or ‘yyyy’, all same

4. Datediff of 2 datetime ( =2nd-1st, result is + or – interger)

select DATEDIFF(mi,GETDATE()+1.0/24,  GETDATE()-1.0/24)  -- return -120
select DATEDIFF(dd,'2019-11-23', '2019-12-23')  --return 30

5. Generate any datetime

select cast('2019-10-23 23:30:59:883' as datetime) --'yyyy-mm-dd' 
select cast('2019/10/23 23:30:59:883' as datetime) --'yyyy/mm/dd' use ':' for ms
select cast('10-23-2019 23:30:59.883' as datetime) --'mm-dd-yyyy' use '.' for ms
select cast('10/23/2019 23:30:59.883' as datetime) --'mm/dd/yyyy'
--same to use convert
SELECT convert(date, '07/23/2009' )

6. Get day/week/month/year part of a datetime

--these pairs are same to get dd,mm,yy part of a datetime, return integer
select Datepart(dd,GETDATE()),day(GETDATE())
select Datepart(mm,GETDATE()),month(GETDATE())
select Datepart(yyyy,GETDATE()),year(GETDATE())

select Datepart(dy,'2019-08-11') --get day of year: 223

select datename(mm,'2000-5-17')  --return 'May'
select datename(weekday,'2000-5-17') --return 'Wednesday'

7. Convert datetime format (input need to be datetime only, result is a string)

-- not working!!!! return '2019-05-17', as it detect input is string, 103 is ignored
select convert(varchar, '2019-05-17', 103)

--input is datetime, reutrn formatted string '17/05/2019'
select convert(varchar, cast('2019-05-17' as datetime), 103)

for a full list of datetime format code (smilar to 103) 

DATE ONLY FORMATS
Format # Query Sample
1 select convert(varchar, getdate(), 1) 12/30/06
2 select convert(varchar, getdate(), 2) 06.12.30
3 select convert(varchar, getdate(), 3) 30/12/06
4 select convert(varchar, getdate(), 4) 30.12.06
5 select convert(varchar, getdate(), 5) 30-12-06
6 select convert(varchar, getdate(), 6) 30 Dec 06
7 select convert(varchar, getdate(), 7) Dec 30, 06
10 select convert(varchar, getdate(), 10) 12-30-06
11 select convert(varchar, getdate(), 11) 06/12/30
12 select convert(varchar, getdate(), 12) 061230
23 select convert(varchar, getdate(), 23) 2006-12-30
101 select convert(varchar, getdate(), 101) 12/30/2006
102 select convert(varchar, getdate(), 102) 2006.12.30
103 select convert(varchar, getdate(), 103) 30/12/2006
104 select convert(varchar, getdate(), 104) 30.12.2006
105 select convert(varchar, getdate(), 105) 30-12-2006
106 select convert(varchar, getdate(), 106) 30 Dec 2006
107 select convert(varchar, getdate(), 107) Dec 30, 2006
110 select convert(varchar, getdate(), 110) 12-30-2006
111 select convert(varchar, getdate(), 111) 2006/12/30
112 select convert(varchar, getdate(), 112) 20061230
     
TIME ONLY FORMATS
8 select convert(varchar, getdate(), 8) 00:38:54
14 select convert(varchar, getdate(), 14) 00:38:54:840
24 select convert(varchar, getdate(), 24) 00:38:54
108 select convert(varchar, getdate(), 108) 00:38:54
114 select convert(varchar, getdate(), 114) 00:38:54:840
     
DATE & TIME FORMATS
0 select convert(varchar, getdate(), 0) Dec 12 2006 12:38AM
9 select convert(varchar, getdate(), 9) Dec 30 2006 12:38:54:840AM
13 select convert(varchar, getdate(), 13) 30 Dec 2006 00:38:54:840AM
20 select convert(varchar, getdate(), 20) 2006-12-30 00:38:54
21 select convert(varchar, getdate(), 21) 2006-12-30 00:38:54.840
22 select convert(varchar, getdate(), 22) 12/30/06 12:38:54 AM
25 select convert(varchar, getdate(), 25) 2006-12-30 00:38:54.840
100 select convert(varchar, getdate(), 100) Dec 30 2006 12:38AM
109 select convert(varchar, getdate(), 109) Dec 30 2006 12:38:54:840AM
113 select convert(varchar, getdate(), 113) 30 Dec 2006 00:38:54:840
120 select convert(varchar, getdate(), 120) 2006-12-30 00:38:54
121 select convert(varchar, getdate(), 121) 2006-12-30 00:38:54.840
126 select convert(varchar, getdate(), 126) 2006-12-30T00:38:54.840
127 select convert(varchar, getdate(), 127) 2006-12-30T00:38:54.840

 

Delete duplicate rows (entire same or partialy same)

 1. Select duplicate rows based on 1 column

select * from students where id in (
    select id FROM students
    group by id having count(*)>1
)

 2. Select duplicate rows based on multiple columns

select * from students a
right join (
    select firstname, lastname from students
    group by firstname, lastname having count(*)>1
) b
on a.firstname=b.firstname and a.lastname=b.lastname

3. Select rows that has unique combination of colums(filter out all duplicate rows)

select * from students except(
    select a.id --need to select all columns here
          ,a.firstname
          ,a.lastname
          ,a.dob from students a
    right join (
        select firstname, lastname from students 
        group by firstname, lastname having count(*)>1
    ) b
    on a.firstname=b.firstnameand a.lastname =b.lastname 
)

4. Select/delete rows of totally identical values

select distinct * from tableName --save the result equals to delete duplicated rows already

5. Delete duplicate rows in table which has unique id

delete from #temp
where id not in(
    select   max(id)   from   #temp
    group   by   col1, col2 --the columns used when checking duplicate
    having count(*)>1
)

6. Delete duplicate rows in table which does not have id

6.1 Delete directly from original table by “Partition” keyword

WITH tempVw AS (
    SELECT 
        *,
        ROW_NUMBER() OVER ( --over() is required for Row_Number()
            PARTITION BY --this reset the rowNumber to 1 for different group
                col1, col2 --which used as identifier to check duplicate
            ORDER BY  --order by is required in Over()
                col1, col2 --keep same as above
        ) row_num
     FROM 
        YourTable
)
delete FROM tempVw WHERE row_num > 1
select * from YourTable --duplicated rows should be removed in original table

6.2 Add unique ID first so it is similar as point 5

--Use views to add rowId for table without unique id
with tempVw as(
    select ROW_NUMBER() over (order by SurveyTypeid, surveyid ) as rowid,*
    from YourTable
)
--define 2 views together, tempVw2 is all duplicated rows
,tempVw2 as (
    select rowid,a.col1,a.col2
    from tempVw a
    right join (
        select col1, col2 from tempVw
        group by col1, col2 having count(*)>1
    ) b
    on a.col1=b.col1 and a.col2=b.col2
) 

--query after view, delete rows in view will delete original table
delete  from tempVw where rowid in (
    --return all duplicated rows except 1 row for each group that we will keep
    select rowid from tempVw2 where rowid not in (
        --return 1 row for each identifier of duplicated rows
        select min (rowid) from tempVw2 group by col1, col2 having count(*)>1
    )
)
select * from YourTable --duplicated rows should be removed in original table

 

 

Except (check difference between 2 tables of same colums) & Intersect

1. Rows which included in A but not B

Select * from A except Select * from B 

2. Return any diff bewteen A and B 

Select * from A except Select * from B union all Select * from B except Select * from A  

3. Return duplicated rows between A and B

Select * from A Intersect Select * from B

 

 

EXEC output to Variable

declare @temp table(id int,Name varchar(50),sex varchar(10))
declare @sql varchar(max)= 'select id,name,''male'' from student where id<3'
insert into @temp exec (@sql)

 

 

Exists

1. To add any condition for the select (Same as if) 

Select col1, col2 from A where exists (Select 1 from B where id=99) --inside exists you can select 1 or anything, it will return TRUE equally

2. To select new user in A but not in B

Select id, name from A where not exists (Select 1 from B where B.id=A.id) 

--this equals to use IN keyword
Select id, name from A where id not in (Select id from B) 

 

 

Import data from excel

SELECT * --INTO #Cars
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0 Xml;HDR=YES;Database=C:\cars.xlsx','SELECT * FROM [sheet1$]');

 

 

Insert into 

1. Mutiple rows with values

insert into #temp(id,name) values (1,'Alice'),(2, 'Jack')

2. From existing tables

insert into #temp(id,name, sex) select id, name,'male' from students where sex=1 

3. From exec (Assign EXEC output to Variable)

declare @temp table(id int,Name varchar(50),sex varchar(10))
declare @sql varchar(max)= 'select id,name,''male'' from student where id<3'
insert into @temp exec (@sql)

 

 

Join

1. cross join

(https://blog.csdn.net/xiaolinyouni/article/details/6943337)

Select * from A cross join B
Select * from A,B --same as above

cross join

 

 

 2. Left join, right join, inner join

Left join: contains all rows from left table A, if A.key=B.key, return result in new table, if multiple B.key match A.key, return multiple rows, if no B.key match, return row with null values

 inner join: only return if A.key=B.key, can be one to one or one to many

 

 

Like and Regex

(http://www.sqlservertutorial.net/sql-server-basics/sql-server-like/)

  • The percent wildcard (%): any string of zero or more characters.
  • The underscore (_) wildcard: any single character.
  • The [list of characters] wildcard: any single character within the specified set.
  • The [character-character]: any single character within the specified range.
  • The [^]: any single character not within a list or a range.

 Not start with special symbol, 3rd character is number or letter

Select * from where name LIKE ' [^.$#@-]_ [a-z0-9]%'

 

 

Login history delete for SSMS

C:\Users\*********\AppData\Roaming\Microsoft\SQL Server Management Studio\18.0\UserSettings.xml

  • Open it in any Texteditor like Notepad++
  • ctrl+f for the username to be removed
  • then delete the entire <Element>.......</Element> block that surrounds it.

 

 

Random id (GUID), string, number

1. Random Guid

select NEWID() --315FC5A3-BE07-41BB-BE4F-75055729FA5B

2. Random string

SELECT CONVERT(varchar(255), NEWID())

3. Random number (round to integer)

SELECT RAND() -- 0<=decimal<1 
SELECT RAND()*15+5; -- 5<=decimal<20 (if include 20 need *16)

SELECT FLOOR(22.6) --22
SELECT CEILING(22.6) --23
SELECT ROUND(22.6,0) -- 23.0
SELECT ROUND(22.6,-1) --20.0 

 

 

Short Keys for text selection

(https://www.mssqltips.com/sqlservertip/2786/column-and-block-text-selection-using-sql-server-management-studio/)

1. Using SHIFT+ALT+(arrow key or cursor) to Select block of values among multiple rows

ssms shift alt select

2. Using CTRL+SHIFT+END to Select Text till end (CTRL+ END can move cursor to end)

ssms ctrl shift end to select

3. Using CTRL+SHIFT+HOME to Select Text till start (CTRL+HOME can move cursor to end)

ssms ctrl shift home select

4. User CTRL+ arrow key can move cursor jump between words not letters

 

 

String edit

Note: SQL index start from 1 not 0

1. left and right

select left('hello world',5) --return: hello
select right('hello world!',6) --return:world!

2. Substring

select substring('hello world',7,5) --return: world

3. Replace (by expression or by index)

select REPLACE('123456','34','new') --return 12new56
select stuff('123456',3,2,'new') --same as above, start index=3, length=2

4. Split (not exist in sql, need use LEFT+ RIGHT + CHARINDEX)

--split 'hello world' by space
select left('hello world',CHARINDEX(' ','hello world')-1) 
select right('hello world',len('hello world')-CHARINDEX(' ','hello world'))

5. Delete white space

SELECT LTRIM('   Sample   '); --return 'Sample '
SELECT RTRIM('   Sample   '); --return ' Sample'

6. Delete enter, tab, space

--char(13)+CHAR(10) = enter
print 'first line'+char(13)+CHAR(10)+'Second line' --2 lines
--char(9) is tab, the outsode replace delete all space
print REPLACE(REPLACE(REPLACE(REPLACE('first line
Second line',CHAR(13),''),CHAR(10),''),CHAR(9),''),' ','')

 7. Search a regex in string

SELECT PATINDEX('%[mo]%', 'W3Schools.com'); --return m or o which appear first

8. Repeat string a few times

select REPLICATE('hello world ',3) --return: hello world hello world hello world  

9. Revers a string by characters

select REVERSE('1234567') --return 7654321

10. Create an empty fixed length string (only contains spaces)

select 'a'+SPACE(5)+'b' --return a     b

 

 

Top

select 2nd high 

 

Transaction

1. Begin, rollback,commit tran

Declare @isDebug bit=1
begin tran

-- insert/update/delete queries    

if @isDebug=1 --test run
begin
    rollback tran
end
else -- prod run
begin
    commit tran
end

2. trasaction with try/catch

Declare @isDebug bit=1
BEGIN TRY
    BEGIN tran    
        if @isDebug=0 --test run
        begin 
            -- insert/update/delete queries    
        end
        else --prod run
        begin
            -- insert/update/delete queries
        end

    COMMIT tran --commit if above code has no error
END TRY
BEGIN CATCH
    ROLLBACK tran --if any error jump to this to rollback
    select ERROR_NUMBER() as ErrorNumber, ERROR_MESSAGE() as ErrorMessage, ERROR_PROCEDURE() as ErrorProcedure
END CATCH

 

 

 Union, Union All

1. Union not return duplicated rows (by duplicated mean all the values are exactly same)

2. Union All return all rows include duplicated rows

3. Both Union and Union all need to have exactly same number of total columns (col name can be diff but type need to be same)

4. Union All is much faster than Union

 

 

Update one colomn from column in another table

UPDATE  a
SET     a.marks = b.marks
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

 

 

View (with … as )  

**delete or update view will influence original table, delete or update or insert values will influence on view

with StudentVw as(
    select top 100 ROW_NUMBER() over (order by SurveyTypeid, surveyid ) as rowid,*
    from ##temp order by channelid -- if use order by must have top keyword
)
select * from StudentVw --must come with a query and only 1 query

 

版权声明:本文为hytvszz原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/hytvszz/p/11712541.html