印象里边最早接触触发器是在耿建玲的视频里边见到的,但是完全不理解,但是在实现机房收费系统的时候,就发现原来SQL Server中还有这么一个强大的功能,简直是和存储过程合称为最佳兄弟二人组。 首先我们看看触发器是什么? 触发器,因为我先认识的存储过程+
印象里边最早接触触发器是在耿建玲的视频里边见到的,但是完全不理解,但是在实现机房收费系统的时候,就发现原来SQL Server中还有这么一个强大的功能,简直是和存储过程合称为最佳兄弟二人组。
首先我们看看触发器是什么?
触发器,因为我先认识的存储过程+事务,所以我在这里把他称为存储过程的小兄弟,至于为什么,因为他们真的很像,对于存储过程,大家可以在http://blog.csdn.net/lovemenghaibin/article/details/38235817了解,这里就不详细的介绍了,但是触发器是什么呢?
触发器是SQL Server提供给程序员和数据分析员来保证数据完整性的一种方式,它就是与表事件相关的特殊存储过程。触发器不能被直接执行,只能为表上的Insert\Update\Delete事件所触发。它也不能传递或接受参数。
触发器可以查询其他表,而且可以包含复杂的SQL语句。它们主要用于强制服从复杂的业务规则或要求。例如:您可以根据客户当前的帐户状态,控制是否允许插入新订单。 比如说,我这里有两张表,一张是充值表(Recharge_Info),一张是学生表(Student_Info),如果我们要进行充值行为,也就是要进行两个动作,第一为学生表的钱加上充值的钱,第二就是为充值表里边添加一条记录,那么如果要完成这个操作,我们需要两步,更新和插入信息,也就说我们会这样 insert Recharge_Info into (cardID,addMoney...) values(@cardID,addMoney...) Update Student_Info set Cash=Cash+addMoney where cardID=@cardID这个过程如果需要执行多次呢,大家每次都要用两条语句来组合这一个过程,是不是麻烦了点,于是现在就有了触发器这个过程,那么我来为大家来展示一下触发器的相同实现。
CREATE TRIGGER [dbo].[TR_charge_U]<span style="white-space:pre"> </span>--创建触发器 <span style="white-space:pre"> </span> ON [dbo].[T_Recharge]<span style="white-space:pre"> </span>--在T_ReCharge表 for insert<span style="white-space:pre"> </span>为了插入数据而需要执行的操作 AS --定义一些参数 declare @cardID char(10)<span style="white-space:pre"> </span>--卡号 declare @cash decimal(10, 2)<span style="white-space:pre"> </span>--卡内余额 declare @addmoney decimal(10, 2)<span style="white-space:pre"> </span>--充值金额 if UPDATE(cash) BEGIN select @cardID =CardID from inserted <span style="white-space:pre"> </span>--选择充值表中的卡号 select @addmoney=cash from inserted --选择我们充值表中的充值金额 select @cash =T_card.cash from T_Card <span style="white-space:pre"> </span>--选择卡内的余额 update T_Card set Cash=@cash+@addmoney where cardID =@cardID END </span>这里我们大家解释一下,这个流程是怎么回事,首先我们要执行的语句就是insert Recharge_Info into (cardID,addMoney...) values(@cardID,addMoney...),那么触发器当你在插入数据的时候,就会将信息保存到Inserted中,然后我们再根据需要把里边的数据取出来,用来更新我们需要更新的表。 在触发器中,我们有两张表,一张是deleted表,一张Inserted表,这两张是虚拟表,用用完之后数据库会自动删除。 下面我用表格的形式将他们的用处展现出来
对表的操作 |
Inserted逻辑表 |
Deleted逻辑表 |
增加记录(insert) |
存放增加的记录 |
无 |
删除记录(delete) |
无 |
存放被删除的记录 |
修改记录(update) |
存放更新后的记录 |
存放更新前的记录 |
create trigger tgr_classes_insert on classes for insert --插入触发 as --定义变量 declare @id int, @name varchar(20), @temp int; --在inserted表中查询已经插入记录信息 select @id = id, @name = name from inserted; set @name = @name + convert(varchar, @id); set @temp = @id / 2; insert into student values(@name, 18 + @id, @temp, @id);delete触发器
create trigger tgr_classes_delete on classes for delete --删除触发 as print '备份数据中……'; if (object_id('classesBackup', 'U') is not null) --存在classesBackup,直接插入数据 insert into classesBackup select name, createDate from deleted; else --不存在classesBackup创建再插入 select * into classesBackup from deleted; print '备份数据成功!';update触发器
create trigger tgr_classes_update on classes for update as declare @oldName varchar(20), @newName varchar(20); --更新前的数据 select @oldName = name from deleted; if (exists (select * from student where name like '%'+ @oldName + '%')) begin --更新后的数据 select @newName = name from inserted; update student set name = replace(name, @oldName, @newName) where name like '%'+ @oldName + '%'; print '级联修改数据成功!'; end else print '无需修改student表!';一个触发器,一个存储过程,一个全自动,一个任意调用,都能让程序运行的更快,占用的资源更少。尽管看上去也很像,功能貌似给我们减少了很多的压力,但是在写的时候,或者说是在设计数据库的时候,我们还是要谨慎的用,否者我们会给软件以后的运行带来难以想象的痛苦。

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

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

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

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!

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.

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor
