search
HomeDatabaseMysql Tutorial sql server常用知识点

sql server常用知识点

Jun 07, 2016 pm 05:37 PM
serverCommonly usedKnowledge points

--删除表 use [20130823_Recource] go drop table my_table1,my_table2,My_table3 --创建表 use [20130823_Recource] go if(exists(select * from sys.objects where)) drop table Student1 go create table Student1 ( Id int primary key identity(1,2) no

--删除表

use [20130823_Recource]

go

drop table my_table1,my_table2,My_table3

--创建表

use [20130823_Recource]

go

if(exists(select * from sys.objects where))

drop table Student1

go

create table Student1

(

Id int primary key identity(1,2) not null,

Name nvarchar(30) not null,

Age int not null,

MyMoney decimal ,

CreateDateTime datetime default getdate()

)

--插入数据

insert into Student values('zhangsan',34,2300,GETDATE())

insert into Student

select 'zhangsi',23,4300 ,GETDATE()union

select 'zhangwu',33,5400,GETDATE() union

select 'zhanghong',12,2300,GETDATE()

--修改数据

update Student set MyMoney=10000 where Age=12

--删除数据

delete Student  where Age=12

truncate table student

--存储过程

if(exists(select * from sys.objects where))

drop proc proc_Name

go

create proc proc_Name(@number int,@number1 int output)

as

begin

select @number1=su.MyMoney from Student as su where su.Id=@number

end

--执行存储过程

declare @num int

exec proc_Name 3,@num output

print @num

--函数

if(exists(select * from sys.objects where))

drop function function_Name

go

create function function_Name(@number int)

returns int

as

begin

declare @number1 int

select @number1=su.MyMoney from Student as su where su.Id=@number

return @number1

end

--执行函数

select dbo.function_Name(3)

--视图

if(exists(select * from sys.objects where))

drop view view_Name

go

create view view_Name

as

select * from Student where ID=3

--执行函数

select * from view_Name

--游标

declare cursor_name cursor scroll for

select su.Name from student as su

open cursor_name

declare @Name nvarchar(20)

fetch last from cursor_name into @Name

print @Name

fetch absolute 3 from cursor_name into @Name

print @Name

fetch relative 1 from cursor_name into @Name

print @Name

fetch prior from cursor_name into @Name

print @Name

fetch first from cursor_name into @Name

while(@@FETCH_STATUS=0)

begin

print @Name

fetch next from cursor_name into @Name

end

close cursor_name

deallocate cursor_name

--事务

begin tran tran_Name

declare @error int

set @error=0

begin try

update Student set MyMoney=MyMoney+1000 where ID=1

set @error=@error+@@ERROR;

update Student set MyMoney =MyMoney -1000 where ID=2

set @error=@error +@@ERROR;

end try

begin catch

print '错误号:'+error_number()+'错误信息:'+error_message()

set @error=@error+1;

end catch

if(@error>=1)

begin

rollback tran

print '失败'

end

else

begin

commit tran

print '成功'

end

--触发器

if(exists(select * from sys.objects where))

drop trigger trigger_Name

go

create trigger trigger_Name

on student

for delete

as

insert into Student values('zhangsss',11,3400,GETDATE())

--执行触发器

delete Student where ID=1

--排名

select *,ROW_NUMBER() over(partition by name order by id) as ran from Student

select *,RANK() over(order by id) as ran from Student

select *,DENSE_RANK() over(order by id ) as ran from Student

select *,NTILE(2) over(order by id) as ran from Student

--开窗函数

Count(*)

--集合

select * from Student

union--合并

select * from Student1

select * from Student

intersect--交集

select * from Student1

select * from Student

except--除去

select * from Student1

--连接

select su.name,su1.Name from Student as su

inner join Student1 as su1

on su.id=su1.Id

 

select su.name,su1.Name from Student as su

left join Student1 as su1

on su.id=su1.Id

 

select su.name,su1.Name from Student as su

right join Student1 as su1

on su.id=su1.Id

 

--case

select *,case

when MyMoney

when 2500

when 4500

end as ran

 from Student1

 

select distinct top 2 * from Student --top,distinct

select isnull(null,2) --判断是否为null

select getdate() --获得日期

select datename(DAY,GETDATE())--获得日期的某一字段

select dateadd(MONTH,1,GETDATE()) --当前日期加

 

select COUNT(*),AVG(su.MyMoney),SUM(su.MyMoney),MIN(su.MyMoney),MAX(su.MyMoney) from Student as su --系统函数

 

select * from Student su where su.Id5 -- 符合:、、

select * from Student su where su.Name like'%wu'--模糊查询:%、_、[]、^

select * from Student su where su.Id between 2 and 6 -- between and

select * from Student su where su.Id in(3,4,5)--in()

select Age from Student su group by su.Age having Age>22 --筛选分组

select * from Student su order by su.Id desc--排序

 

 

触发器的两个重要的表

对表的操作

Inserted逻辑表

Deleted逻辑表

增加记录(insert)

存放增加的记录

删除记录(delete)

存放被删除的记录

修改记录(update)

存放更新后的记录

存放更新前的记录

 

触发器回滚

 

if(exists(select * from sys.objects where name = 'tr_Valid'))

drop trigger tr_Valid

go

create trigger tr_Valid

on mymsg

for insert

as

declare @age int;

select @age=age from inserted

if(@age>50)

begin

insert into mymsg select Name,Age from inserted

end

else

begin

print 'age数值不正确'

rollback tran;--数据不正确,就执行回滚业务

end

 

 

insert into mymsg values('zl68',51) --测试

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function