Useful SQL statements (deleting duplicate records and shrinking logs)

Source: Internet
Author: User
Tags rtrim
These are some useful SQL statements. For more information, see.

These are some useful SQL statements. For more information, see.

Delete duplicate records and save the non-Repeated Records in TABLE_NAME to # TABLE_NAME

Select distinct * into # table_name from table_name
Delete from table_name
Select * into table_name from # table_name
Drop table # table_name

This is related to the "select into" option, which can be in the database attribute
In the dialog box, check this item, or execute it in Query Analyzer.
Execute sp_dboption 'db _ name', 'select into', 'true'
Enable. The default value is disabled.


**************************************** ***************
Shrink transaction logs (multiple executions)

Backup log register with NO_LOG
Backup log register with TRUNCATE_ONLY
Dbcc shrinkdatabase (register)

More useful SQL statements
/* SQL syntax learning */

/* Function learning ---------------------------------------*/

Obtain the current time (hour/minute/second): select convert (varchar (10), getdate (), 8)
Obtain the current year, month, and day: select convert (varchar (10), getdate (), 120)
Obtain the current year and month: select convert (varchar (7), getdate (), 120)
Obtain the current year and month: select convert (varchar (10), year (getdate () + '-' + convert (varchar (10), month (getDate ()))

Select cast (B as integer) as bb from table1 where B = '11'

Select a, case B when '11' then' detailed 'when' 22 'then', 'else', 'hangzhou' end as conversion, c from table1

Select a, B, case when c = '000000' then' detail 'when c = '000000' then' Haha 'else' Haha 'end as conversion 1 from table1

Get current time: print current_timestamp

/*---------------------------------------------*/

----------------- Output the SQL query to the txt text file -------------------------------------------
EXEC master.. xp_mongoshell 'bcp database name. dbo. Table name out d: \ 1.txt-c-q-U "sa"-P "password "'

Bytes ---------------------------------------------------------------------------------------

--------------------------- Usage of round beigin ------------------------------
Declare @ s float
Set @ s = 0.1566134
Print round (@ s, 3)
--------------------------- Round usage end ---------------------------------

------------------------------ Automatically contract the database begin -----------------------------

EXEC [master] .. sp_dboption [Database Name], 'autoshrink ', 'true'

-------------------------------- Automatically contract the Database end -----------------------------


------------------------------- Remove invalid character begin --------------------------
Declare @ s varchar (20)
Set @ s = ', 1-> 1 ,'
While (left (@ s, 1) = ',')
Set @ s = stuff (@ s, 1, 1 ,'')
While (right (@ s, 1) = ',')
Set @ s = stuff (reverse (@ s), 1, 1 ,'')
Select @ s
------------------------------- Remove invalid characters at the beginning and end --------------------------


------------ Example of deleting a duplicate record in a database (and retaining only one valid record -----------------
Create table
(
UserID int identity (1, 1 ),
UserName varchar (20 ),
UserPwd varchar (20 ),
UserEmail varchar (50)
)
Insert into A (userName, userpwd) select 'qin', 'qin' union all select 'qin', 'qin1' union all select 'qin', 'qin1'
Select * from

-- Method one
Delete from A where userid not in (select min (userid) as userid from A group by username, userpwd)

-- Method two
Delete from A where exists (select * from A B where a. username = B. username and a. userpwd = B. userpwd and a. userid <B. userid)

-- Method three
Delete from a where userid not in (select min (userid) from A B where. username = B. username and. userpwd = B. userpwd and. userid> B. userID)

Select * from
Drop table

------------ Example of deleting a duplicate record in a database (and retaining only one valid record -----------------



----------------------------- Application of the same origin (find the path between the start and end -----------------------------
Create table t
(St varchar (20), ed varchar (20), km int)
Go
Insert t values ('A', 'B', 1000)
Insert t values ('A', 'C', 1100)
Insert t values ('A', D', 900)
Insert t values ('A', 'E', 400)
Insert t values ('B', 'd, 300)
Insert t values ('D', 'F', 600)
Insert t values ('E', 'A', 400)
Insert t values ('F', 'G', 1000)
Insert t values ('C', 'B', 600)
Go
-- Display insert value
Select * from t
Go

-- Create a function
-- The function returns a table, which is inserted at different layers according to the actual situation. The generated table can be fully utilized.
Create function f_go (@ col varchar (10 ))
Returns @ t table (col varchar (30), st varchar (20), ed varchar (20), km int, level int)
As
Begin
Declare @ I int
Set @ I = 1
Insert @ t select st + '-' + ed, *, @ I from t where st = @ col
While exists (select * from t a, @ t B where
B. ed = a. st and B. level = @ I and B. ed <> @ col)
Begin
Set @ I = @ I + 1
Insert @ t
Select B. col + '-' + a. ed, a. st, a. ed, B. km + a. km, @ I from t a, @ t B
Where B. level = @ I-1 and B. ed = a. st and B. ed <> @ col
End
Return
End
Go

-- Call
-- Select * from dbo. f_go ('A ')
Select col, km from dbo. f_go ('A ')

-- Delete the environment
Drop function f_go
Drop table t

----------------------------- Application of the same origin (find the path between the start and end -----------------------------



-------- Sort the latest first N records by category, put the same class together, and count the number of items in the same class -------------
Create table t
(
ClassName varchar (50 ),
ClassCode varchar (10 ),
ClassID int identity (1, 1)
)
Insert into t
Select 'cccccc1', '002' union all
Select 'aaa', '001' union all
Select 'bbbbb', '001' union all
Select 'aaaaa1', '002 'union all
Select 'cccc', '001' union all
Select 'ddddd', '001' union all
Select 'bbbb1', '002' union all
Select 'dddd1', '002'
Select * from t
Select ClassCode = (case when exists (select 1 from t t1 where classCode = t1.ClassCode
And ClassID <t1.ClassID)
Then ''else ClassCode end), ClassName from t order by ClassCode, ClassID desc

Select count (*), classCode from (select top 100 percent ClassCode = (case when exists (select 1 from t t1 where classCode = t1.ClassCode
And ClassID <t1.ClassID)
Then ''else ClassCode end), ClassName from t order by ClassCode, ClassID desc) a group by classcode

Select classCode, className from t order by classCode, classID desc
Drop table t

-------- Sort the latest first N records by category, put the same class together, and count the number of items in the same class -------------


------------- Same as above, calculate by category, add the other content of the same category and concurrently add it to a field ------------------
Create table tb (ProductID varchar (10), PositionID varchar (10 ))
Insert into tb
Select '200', 'a1'
Union all select '200', 'b2'
Union all select '200', 'c3'
Union all select '20180101', 'd4'
Union all select '000000', 'e5'
Go

Create function dbo. fc_str (@ ProductID varchar (10 ))
Returns varchar (100)
As
Begin
Declare @ SQL varchar (1000)
Set @ SQL =''
Select @ SQL = @ SQL + ',' + cast (PositionID as varchar (20) from tb where ProductID = @ ProductID
Return stuff (@ SQL, 1, 1 ,'')
End
Go

Select ProductID, dbo. fc_str (ProductID) as PositionID from tb group by ProductID

Drop table tb

Drop function dbo. fc_str

------------- Calculate by category, add the other content of the same class, and concurrently add it to a field ------------------



-- Obtain the first n records of each class (top n records for each class)
-- If there are multiple classes in the database, you need to retrieve the first n records of each class. The following statements can be used:
Create Table TEST
(ID Int Identity (1, 1 ),
H_id Int)
"Insert TEST Select 100"
Join All Select 100
Join All Select 100
Join All Select 101
Join All Select 101
Join All Select 101
Join All Select 100
GO
-- Method 1:
Select * From test a Where Id In (Select TOP 3 ID From TEST Where h_id = A. h_id)
-- Method 2:
Select * From test a Where Not Exists (Select 1 From TEST Where h_id = A. h_id And ID2)
-- Method 3:
Select * From test a Where (Select Count (*) From TEST Where h_id = A. h_id And IDGO
Drop Table TEST
GO


-- Group statistics: counts the number of data in each segment.
-- This is applicable to general score statistics.
Declare @ t table (id int, weight int)
Insert into @ t select 1, 20
Insert into @ t select 2, 15
Insert into @ t select 3, 5
Insert into @ t select 4, 60
Insert into @ t select 5, 12
Insert into @ t select 6, 33
Insert into @ t select 7, 45
Insert into @ t select 8, 59
Insert into @ t select 9, 89
Insert into @ t select 10,110

Declare @ p int
Set @ p = 10
Select
Rtrim (p * @ p) + '-' + rtrim (p + 1) * @ p "> p * @ p) + '-' + rtrim (p + 1) * @ p) as p,
Num
From
(Select (weight/@ p "> weight/@ p) as p, count (*) as num from @ t where weight between 10 and 100 group by (weight/@ p "> weight/@ p)


-------------------------- In THE in statement, you can only use the custom sorting begin --------------------------------
Declare @ t table (id int, weight int)
Insert into @ t select 1, 20
Insert into @ t select 2, 15
Insert into @ t select 3, 5
Insert into @ t select 4, 60
Insert into @ t select 5, 12
Insert into @ t select 6, 33
Insert into @ t select 7, 45
Insert into @ t select 8, 59
Insert into @ t select 9, 89
Insert into @ t select 10,110
-- The SQL statements in the in statement are sorted by id by default.
Select * from @ t where id in (2, 4, 3)
-- This method can be used to display data in the order of input IDs.
Select * from @ t where id in (2, 4, 3) order by charindex (rtrim (id), ', 2, 4, 3 ,')

-------------------------- In THE in statement, only use the custom sorting end --------------------------------

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.