Common Sql Server grammar

  I often use Sql Server database , summed up some commonly used Sql Server syntax including addition, deletion, search and modification, stored procedures, triggers and other syntax. Provide novice learning and grammar search, the file is short, save a lot of time to find information, the shortcomings need to be improved.

                                      
                                                                  --A collection of common Sql Server syntax --build
database command
if exists (select * from sys.databases where name='test')
drop database test --if there is a database with the same name, delete the database
Go
create database test on primary(
name= N'test', --database name
filename=N'D:\test.mdf', --file address
size=3MB, --initial size 3MB (cannot be less than 3MB)
maxsize=unlimited, --file maximum size
filegrowth =1MB --file growth rate
)
log on --database log file
(
name=N'test_log', --log file name
filename=N'D:\test_log.ldf', --log file address
size=1MB, -- - The initial size of the log file is 1MB
maxsize=1GB, -- the maximum size of the log file
filegrowth=10% --log file growth rate
) --data
                               type
--bit--smallint--int --char--float--double
--nchar--datetime--smalldatetime--varchar--nvarchar-- image
--money--smallmoney--binary--varbinary--text--decimal(3,3) --create
table
if exists(select * from sys.objects where name='mytest' and type='U')
drop table mytest
go
create table mytest
(
id int identity(1,1) primary key, --primary key auto-increment
[name] varchar(50) unique, --unique value cannot be repeated
[sex] varchar(2) not null default( 'male'), --default is 'male'
address varchar(343) not null, --cannot be empty
age smallint check(age<120 and age>0),--Constraints cannot be greater than 120 and less than 0 years old
date datetime
)
insert into mytest([name],[sex],address,age,date) values('yi','男','于璐璐',39,getdate())
insert into mytest([name],[sex],address,age,date) values('yib','男','于璐璐',3,getdate())
insert into mytest([name],[sex],address,age,date) values('yibi','女','于璐璐',34,getdate())
insert into mytest([name],[sex],address,age,date) values('yibin','女','于璐璐',25,getdate())
insert into mytest([name],[sex],address,age,date) values('yibing','男','易津锐',30,getdate())
insert into mytest([name],[sex],address,age,date) values('yibing2','男','易津锐',26,getdate())
insert into mytest([name],[sex],address,age,date) values('y2','男','津锐',26,getdate())

go
--显示年龄在20-30之间的信息
select * from mytest where id not in(select id from mytest where age<30 and age>20)
select * from mytest where id not in(select id from mytest where age between 20 and 30)


--Show duplicate records method 1

select count(*) the same number of addresses from mytest group by address having count(address)>1
-- display duplicate records method 2

select a.* from mytest a where exists(
select 1 from mytest b where a.id<>b.id and a.address=b.address )

--显示重复的记录方法三
select distinct t.id,t.[name], max(t.address) from mytest t, mytest t2
group by t.id,t2.id,t.address,t2.address,t.[name] having t.id<>t2.id and t.address=t2.address

--Display duplicate records method four
select distinct t1.* from mytest t1,mytest t2 where t1.id<>t2.id and t1.address=t2.address
--select * from table name --
GROuP BY name--
HAVING COUNT (name)>=2
-- display duplicate records method five

select * from mytest where --display
the number of duplicate records method
select count(*) the same number, a.address from (select t.* from mytest t where exists(select id from mytest t2 where t.id<>t2 .id and t.address=t2.address))as a
group by a.address
-- display custom serial number
select row_number() over(order by date ) serial number,* from mytest

select * from mytest t1 where exists(select 1 from mytest t2 where t1.id<>t2.id and t1.address=t2.address)

select * from mytest where address like '_jin%' -- fuzzy query %%,_%,%_
select * from mytest where date between '2011-09-22 16:01:07.678' and '2011-09-29 ' --The value between the specified range
select * from mytest where date >'2011-09-25 16:01:07.678' and date<'2011-09-26' --The value between the specified range
select distinct * from mytest --distinct eliminate duplicate records
select * from mytest order by id asc --ascending
select * from mytest order by id desc --descending
select id,sex,age,count(*) as number,address from mytest group by sex ,age,address,id
having id='1' --grouping
                              --data query
select t.*,t2.* from mytest t left join mytest t2 on t.id=t2.id--left join
select t.* ,t2.* from mytest t right join mytest t2 on t.id=t2.id--右连接
select t.*,t2.* from mytest t full join mytest t2 on t.id=t2.id--完全连接
select * from mytest where id not in(select id from mytest where id>2 and sex='女')--字查询
select * from mytest where id in(select id from mytest where id>2 and sex='女')--字查询
select * from mytest where exists(select id from mytest where id>2 and sex='女')--字查询
select * from mytest where not exists(select id from mytest where id>2 and sex='女')--字查询
select * from mytest where id < any(select id from mytest where id>2 and sex='女')--字查询
select * from mytest where id < all(select id from mytest where id>2 and sex='女')--字查询
< any--小于查询结果的某个值  >=any <=any <>any >any
< all--小于查询结果的所有值  >=all <=all <>all >all
select * from mytest union select * from mytest
--Joint query, automatically filter duplicate values, get the union of the two tables, sort by the first column, and merge the data of the two tables, provided the two tables have the same structure
select * from mytest union all select * from mytest--Joint query ,Do not filter duplicate values, do not sort
select * from mytest intersect select * from mytest --Joint
query, automatically filter duplicate values, get the intersection of two tables, and sort the data that exists at the same time
select id,[name],[sex] ,address,age into mytest3 from mytest
--select into syntax, copy and backup mytest table to mytest3 table --row and
column conversion
select * from mytest3 --method
one case function
select id,address,age,
   (case sex when 'male ' then [name] else'' end) male,
   (case sex when 'female' then [name] else'' end) female
from mytest --method
one case function
select id,address,age,
   (case when sex=' Male' then [name] else'' end) Male,
   (case when sex='female' then [name] else'' end) female
from mytest
--方法二pivot函数
select * from mytest pivot(max([name]) for sex in(男,女))a
--方法三left join左连接
select r.id,address,age,男,女 from mytest r
left join
(select id,[name] as 男 from mytest where sex='男') t on r.id=t.id
left join
(select id,[name] as 女 from mytest where sex='女') t2 on r.id=t2.id


                                --Advanced T_sql --declare
variable
declare @str varchar(30)
set @str='123'
--assignment print @str --print output
select @str --table output --global
variable @@form
 select @@ identity
 select @@connections
--function
select abs(-23.44) --take the absolute value 23.44
select ceiling(34.56) --return the smallest integer greater than or equal to the parameter 35
select floor(34.56) --return the largest integer less than or equal to the parameter 34
select round(2312.32534,2)--rounding operation, 2 is the reserved decimal place 2312.33000
--string
select ltrim(' 234')--remove the left space
select charindex('a','s3dda33')--return character 'a' at position 5 in the string 's3dda33', counting from 1
select len('234wefwef')--returns the length of the string 9
select substring('we I rweff',3,5)--from the character String position 3 starts to intercept 5 characters and returns 'my rwef'
select stuff('we I rweff', 3, 5, 'replaced')--starting from string position 3 to replace the characters of the five following parameters output 'we has replaced f' --time
function--
datepart time parameter expression
--yy,yyyy(1753-9999)--year--
qq,q(1-4)--quarter--
mm,m(1-12)month
--dy,y(1- 366) Day of the year--
dd,d (1-31) Day of January--
wk,ww (1-7) Day of the week
--hh (0-23) Hours
--mi,n (0-59) minutes
--ss,s (0-59) seconds
--ms (0-999) milliseconds
select getdate() --get the current time
select dateadd(yy,3,'2011-2-2') --Add integer 3 output for yy year 2014-02-02 00:00:00.000
select dateadd(mm,3,'2011-2-2')--Add integer 3 output for mm month 2011-05-02 00: 00:00.000 --time
difference function
select datediff(yy,'1922-1-3','2011-2-3')--returns the time difference of the year of the two time parameters output 89
select datediff(mm,'1922-1 -3','2011-2-3')--returns the time difference of the months of the two time parameters and outputs 1069
select datename(yyyy,'2011-2-3') --return year
select datename(mm,'2011-2-3') --return month
select datename(ww,'2011-2-3') --return Day of the week
select datepart(ss,'2011-2-3 23:44:09') --returns the second integer
select day('2011-2-3 23:44:09') --returns the number of days
select month('2011 -2-3 23:44:09') --return the number of months
select year('2011-2-3 23:44:09') --return the number of years
--system function
select cast(233.44 as int)--cast The function forces the integer 233.44 to be converted to the integer 233 output
select convert(varchar,getdate(),101) as '101'--convert converts time to character output
--aggregation functions
 sum(),max(),min(),avg (),count(),
begin
end--program running range
--case expression syntax
select distinct id,address,age,
   (case sex when 'male'then [name] else'' end) 男,
   (case sex when 'female' then [name] else'' end) female
from mytest --create
                             view
create view v_test
as
select *from mytest --build view v_test --build
                             index
create index sex on mytest(sex)-- Created an index on the sex field of the mytest table
create unique index id on mytest(id)--created a unique index on the id field of the mytest table
create clustered index sex2 on mytest(id)--on the id field of the mytest table Established a clustered index
create nonclustered index sex3 on mytest(id)--established a non-clustered index on the id field of the mytest table
                             --established a stored procedure
if exists(select 1 from sys.objects where [name]='insertest' and type='P')
​​drop procedure insertest
go
create procedure insertest
   @name varchar(30),
   @sex varchar(2)='male', -- the default value is male
   @address varchar(200),
   @age int=25 -- the specified default value is 25
as
begin
   insert into mytest([name],[sex], address,age) values(@name,@sex,@address,@age)
end
go
exec insertest 'Li Lili','male','Room 211, No. 2, Lane 93, Yulin Road',90 --exec executes the stored
                          procedure-- Stored procedure return type
go
if exists(select 1 from sys.objects where [name]='insertest2' and type='P')
​​drop procedure insertest2
go
create procedure insertest2
   @name varchar(30),
   @sex varchar(4) ='male', --default is male
   @address varchar(200),
   @age int=25,--Specify the default value of 25
   @id int output --Define the return type
as
begin
   insert into mytest([name],[sex],address,age) values(@name,@sex,@address,@age)
   set @id=@@identity -- assign the self-incrementing field data to @id and Return  
end
go
declare @putid int
exec insertest2 'Wang Lili','male','XX Road',90,@putid output --exec execute stored procedure
print cast(@putid as varchar) --convert @putid to varchar output              --Store
                            procedure with transaction
go
if exists(select 1 from sys.objects where [name]='insertest3' and type='P')
​​drop procedure insertest3
go
create procedure insertest3
   @name varchar(30),
   @sex varchar(2 )='male', --default is male @address
   varchar(200),
   @age int=25, --specified default is 25
   @id int output --define the return type
as
begin try --start monitoring program
   begin tran --prepare transaction
    insert into mytest([name],[sex],address,age) values(@name,@sex,@address, @age)
    set @id=@@identity --Assign the self-incrementing field data to @id and return  
   commit tran --commit the transaction if there is no error
end try --end the monitoring program
begin catch  
   set @id=-1 --program Error processing starts
   rollback tran -- if the program fails, the transaction is rolled back, and the sql statement inserted into the table is not executed
end catch -- the program error processing ends

                           --Establish a trigger
--inserted table, a copy that is kept before executing (insert) insert or (update) update
--deleted table, a copy that is stored in (delete) delete or (update) update to keep the deleted data copy

-- Relationship between inserted table and deleted table

--trigger type | inserted table | deleted table
--insert | store a copy of the inserted record | none
--update | store a copy of the updated record | store a copy of the original record before the update
--delete | none| Store a copy of the deleted original record

if exists(select * from sys.all_objects where [name]='triggtest' and [type]='TR')
drop trigger triggtest
go
create trigger triggtest
on mytest -- trigger creation object on mytest table
for insert, update, delete -- create an insert, modify, delete type trigger
as
begin
    delete from trigtesttab -- first delete the monitoring table trigtesttab
    insert into trigtesttab -- insert data
    select count(name), avg(age), getdate() from mytest
    group by age --age grouping
end
  --test statement insert into mytest([name],[sex],address,age) values(' pt58
  ','h','t',55)
  delete from mytest where id='1'

--Create trigger status monitoring table
create table trigtesttab
(
namecount int,
ageavg int,
date datetime
)
select * from mytest
select * from trigtesttab --Create
                            column level trigger
if exists(select * from sys.all_objects where [name]= 'triggtest2' and [type]='TR')
drop trigger triggtest2
go
create trigger triggtest2
on mytest -- trigger build object on mytest
for update -- build modification trigger  
as
if update([name]) -- on [ Create a column-level modification trigger on the name] field
begin
  print 'Cannot modify the [name] column'
  rollback tran
end
--test
update mytest set [name]='123' where id='3' -- cannot be modified successfully

--delete trigger with primary foreign key relationship
create table tuser
(
id int primary key identity(1,1),
uname varchar(50),
utele varchar(100)
)
go
create table toorder
(
id int primary key identity(1 ,1),
pname varchar(50),
price decimal(5,2),
number int,
tuser_id int foreign key references tuser(id)--ON DELETE CASCADE plus keywords can automatically delete cascades
)
go
insert into tuser values ('yi','1342424425')
insert into tuser values('yibin','13436546747')
insert into tuser values('yijinrui','13436546747')
go
insert into torder values('net programming','213', '1',1)
insert into torder values('PHP编程','123','1',1)
insert into torder values('Java编程','323','1',2)
insert into torder values('Vb编程','323','1',2)
insert into torder values('jQuery编程','323','2',2)
go
select * from torder
select * from tuser
go
select uname,pname,price,number from torder,tuser where torder.tuser_id=tuser.id

go
create procedure insertuser
   @uname varchar(50),
   @utele varchar(100)
as
   insert into tuser values(@uname,@utele)
go
exec insertuser 'li','11133544'
go
drop trigger deletetuser on tuser
instead of delete -- Create a delete trigger of type instead of delete execution statement
as
declare @uid int --define the id variable of tuser
begin try
 select @uid=id from deleted --get the id of the deleted tuser table
 delete from toorder where tuser_id=@uid   - -Delete the reference id number of the tororder table @uid
 delete from tuser where id=@uid --Execute      the delete action of the main table
end try
begin catch
   rollback tran
end catch
go
--测试
delete from torder where id=1
delete from tuser where id=1
go
year | quarter | month | week | day | hour | minute | second | millisecond
declare @date varchar,@date2 varchar
set @date='2011-2-12 6:34:06'
set @date2='2012-12-10'
select cast(datediff(year,@date,@date2) as varchar)+'年'+
       cast(datediff(month,'2011-2-12 6:34:06','2012-12-10') as varchar)+'月'+
       cast(datediff(day,'2011-2-12 6:34:06','2012-12-10') as varchar)+'天'+
     cast(cast(datediff(hour,'2011-2-12 6:34:06','2012-12-10') as int)%24 as varchar)+'小时'+
     cast(cast(datediff(minute,'2011-2-12 6:34:06','2012-12-10') as int)%60 as varchar)+'分'+
     cast(cast(datediff(second,'2011-2-12 6:34:06','2012-12-10') as int)%60 as varchar)+'second'
 as time difference from tuser

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326150124&siteId=291194637