当前位置:网站首页>Sqlserver regularly backup database and regularly kill database deadlock solution
Sqlserver regularly backup database and regularly kill database deadlock solution
2022-07-05 10:38:00 【Full stack programmer webmaster】
Last Friday, the team leader told me to kill data The deadlock process of the Library , Sometimes writing to the database at the same time will cause this situation , Because I'm not very familiar with databases , Suddenly, the team leader said, and I decided to do something about it , How else can I improve myself ? Not now , Maybe we should study it next time , After pouring it out, it can be used next time , Later, the group leader added :” There is also the problem of regularly backing up the database ”, Do as you say
PS:Sqlserver 2008 R2,windows 8 64 position
1. Backup database
Because you need to back up , We're going to use Sqlserver Agent for , The agent of the default database is not enabled . We need to start it manually .
Execute the backup database script , Now publish the script , In fact, the backup can be realized by replacing the file path and database name that need to be saved in this code . But the purpose of scheduled backup has not been achieved
-- Automatically back up and save the latest 5 Days of SQL Database job script
DECLARE @filename VARCHAR(255)
DECLARE @date DATETIME
SELECT @date=GETDATE()
SELECT @filename = 'G:\ Storage location \ Database name -'+CAST(DATEPART(yyyy,@date) as varchar)+'-'+CAST(DATEPART(mm,@date) as varchar)+'-'+CAST(DATEPART(dd,@date) as varchar)+'.bak'
BACKUP DATABASE [ Database name ] TO DISK = @filename WITH INIT
GO
DECLARE @OLDDATE DATETIME
SELECT @OLDDATE=GETDATE()-5
EXECUTE master.dbo.xp_delete_file 0,N'G:\ Storage location ',N'bak',@olddate,1
2. Regularly back up the specified database
Just opened Sqlserver Agency service , In fact, my own understanding is a timer , Keep performing some tasks assigned by the operator , It feels like an alarm clock , Look at my demonstration steps
First step
The second step
The third step
Step four
Step five
The above steps are to complete the function of regularly backing up the specified database !
**************************************************************************
1. Kill the database deadlock process
Next, I will introduce some methods to kill the database deadlock process
I spent a long time in the afternoon looking for many articles to read , I found that many of them were used master Medium sys.sysprocesses surface (http://msdn.microsoft.com/zh-cn/library/ms179881(SQL.90).aspx) Here attached msdn Explanation of this table , If you don't understand it, please refer to the meaning of each table field .
Refer to the opinions on the Internet , Most of them write a stored procedure in master In the database , Then use the way of homework Kill the deadlock process regularly Of , I think this method is feasible !
Here are stored procedures SQL sentence
-- Database deadlock resolution , Combined with homework ( Baidu ) Realize the process of regularly clearing database deadlock , Stored procedures are placed in master In the database
USE master
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE sp_who_lock
AS
BEGIN
DECLARE @spid INT ,
@bl INT ,
@intTransactionCountOnEntry INT ,
@intRowcount INT ,
@intCountProperties INT ,
@intCounter INT
CREATE TABLE #tmp_lock_who
(
id INT IDENTITY(1, 1) ,
spid SMALLINT ,
bl SMALLINT
)
IF @@ERROR <> 0
RETURN @@ERROR
INSERT INTO #tmp_lock_who ( spid, bl )
SELECT 0, blocked
FROM ( SELECT *
FROM sys.sysprocesses
WHERE blocked > 0
) a
WHERE NOT EXISTS ( SELECT *
FROM ( SELECT *
FROM sys.sysprocesses
WHERE blocked > 0
) b
WHERE a.blocked = spid )
UNION
SELECT spid, blocked
FROM sys.sysprocesses
WHERE blocked > 0
IF @@ERROR <> 0
RETURN @@ERROR
-- Find the number of records in the temporary table
SELECT @intCountProperties = COUNT(*), @intCounter = 1
FROM #tmp_lock_who
IF @@ERROR <> 0
RETURN @@ERROR
IF @intCountProperties = 0
SELECT N' There is no blocking or deadlock information ' AS message
-- Loop start
WHILE @intCounter <= @intCountProperties
BEGIN
-- Take the first record
SELECT @spid = spid, @bl = bl
FROM #tmp_lock_who
WHERE Id = @intCounter
BEGIN
IF @spid = 0
SELECT N' The cause of database deadlock is : ' + CAST(@bl AS VARCHAR(10))
+ N' Process number , It carries out SQL The grammar is as follows '
ELSE
SELECT N' Process number SPID:' + CAST(@spid AS VARCHAR(10))
+ N' By process number SPID:' + CAST(@bl AS VARCHAR(10)) N' Blocking , The execution of its current process SQL The grammar is as follows '
DBCC INPUTBUFFER (@bl )
END
-- Loop pointer down
SET @intCounter = @intCounter + 1
END
DROP TABLE #tmp_lock_who
RETURN 0
END
go
above sql The execution of the statement is completed in master The database generates stored procedures , The calling code is simple
-- perform
EXEC sp_who_lock
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
After the call is completed, all deadlock processes in the database can be killed
Digression : How to determine whether those processes are deadlock processes , This is the key point , stay msdn Chinese vs sys.sysprocesses There is a field in the table blocked This field , Remove all larger than 0 Is the deadlock process data of the database , And then use KILL+SPID( process ID) Execution can kill the deadlock process , These are the main ideas .
2. Kill the database deadlock process regularly
For regularly killing database deadlock processes , Here are two points to note
1. Order of execution , Now? master Database creation stored procedure , Then create the job
2. The execution code of the job , The executing code is to call the stored procedure that kills the deadlock process ( Of the calling stored procedure sql sentence , Cannot include delete stored procedures (DROP xxx) Such a statement is not good , When the job is first executed , The second time, you will report a mistake , It will never succeed
First step
You need to execute the above stored procedure to kill the deadlock process , Only master This stored procedure exists in the database , Can call this stored procedure in the form of a job , Otherwise, the call fails *
The second step
Create a new job , Will just call the... Of the stored procedure SQL Put the statement into New job => Step options => command , Medium will do . The last step Implementation plan Set it according to the actual situation
About Sqlserver The two difficulties of the database were also absorbed by myself this afternoon . In the future, you can also easily deal with similar problems
copyright , If you break the law, you will be prosecuted .
Please explain the original link
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/109840.html Link to the original text :https://javaforall.cn
边栏推荐
- 【js学习笔记五十四】BFC方式
- 爬虫(9) - Scrapy框架(1) | Scrapy 异步网络爬虫框架
- PWA (Progressive Web App)
- Livedata interview question bank and answers -- 7 consecutive questions in livedata interview~
- Workmanager Learning one
- [paper reading] kgat: knowledge graph attention network for recommendation
- How does redis implement multiple zones?
- 请问postgresql cdc 怎么设置单独的增量模式呀,debezium.snapshot.mo
- [observation] with the rise of the "independent station" model of cross-border e-commerce, how to seize the next dividend explosion era?
- 跨页面通讯
猜你喜欢
pytorch输出tensor张量时有省略号的解决方案(将tensor完整输出)
Learning note 4 -- Key Technologies of high-precision map (Part 2)
【观察】跨境电商“独立站”模式崛起,如何抓住下一个红利爆发时代?
Have you learned to make money in Dingding, enterprise micro and Feishu?
[observation] with the rise of the "independent station" model of cross-border e-commerce, how to seize the next dividend explosion era?
Learning Note 6 - satellite positioning technology (Part 1)
Solution of ellipsis when pytorch outputs tensor (output tensor completely)
[dark horse morning post] Luo Yonghao responded to ridicule Oriental selection; Dong Qing's husband Mi Chunlei was executed for more than 700million; Geely officially acquired Meizu; Huawei releases M
Timed disappearance pop-up
Workmanager Learning one
随机推荐
TypeError: Cannot read properties of undefined (reading ‘cancelToken‘)
Node の MongoDB Driver
想请教一下,十大券商有哪些?在线开户是安全么?
【Vite】1371- 手把手开发 Vite 插件
SLAM 01.人类识别环境&路径的模型建立
BOM//
Interview: is bitmap pixel memory allocated in heap memory or native
Glide Mastery
微信小程序触底加载与下拉刷新的实现
How to write high-quality code?
Timed disappearance pop-up
手机厂商“互卷”之年:“机海战术”失灵,“慢节奏”打法崛起
小程序框架Taro
2022年化工自动化控制仪表考试试题及在线模拟考试
ModuleNotFoundError: No module named ‘scrapy‘ 终极解决方式
Learning note 4 -- Key Technologies of high-precision map (Part 2)
Blockbuster: the domestic IDE is released, developed by Alibaba, and is completely open source!
DDOS攻击原理,被ddos攻击的现象
报错:Module not found: Error: Can‘t resolve ‘XXX‘ in ‘XXXX‘
[paper reading] ckan: collaborative knowledge aware autonomous network for adviser systems