* Description: copy a table (only copy structure, source table name: a new table name: B)
Select * into B from a where 1 <> 1
* Description: copy a table (copy data, source table name: A target table name: B)
Insert into B (a, B, c) Select D, E, F from B;
* Description: displays the article, Submitter, and last reply time.
Select a. Title, A. username, B. adddate from Table A, (select max (adddate) adddate from table where table. Title = A. Title) B
* Description: External join query (table name 1: Table A name 2: B)
Select a. a, a. B, A. C, B. C, B. D, B. F from a left out join B on A. A = B. C
* Note: Five minutes in advance of the schedule
Select * from Schedule where datediff ('minute ', F Start Time, getdate ()> 5
* Note: two associated tables are used to delete information that is not in the primary table.
Delete from info where not exists (select * From infobz where info. INFID = infobz. INFID)
* Note :--
SQL:
Select a. Num, A. Name, B. upd_date, B. prev_upd_date
From Table1,
(Select X. Num, X. upd_date, Y. upd_date prev_upd_date
From (select num, upd_date, inbound_qty, stock_onhand
From Table2
Where to_char (upd_date, 'yyyy/mm') = to_char (sysdate, 'yyyy/mm') X,
(Select num, upd_date, stock_onhand
From Table2
Where to_char (upd_date, 'yyyy/mm') =
To_char (to_date (to_char (sysdate, 'yyyy/mm') | '/01', 'yyyy/MM/dd')-1, 'yyyy/mm ')) y,
Where X. num = Y. Num (+)
And x. INBOUND_QTY + NVL (Y. STOCK_ONHAND, 0) <> X. STOCK_ONHAND) B
Where A. NUM = B. NUM
* Note :--
Select * from studentinfo where not exists (select * from student where studentinfo. id = student. id) and Department name = '"& strdepartmentname &"' and major name = '"& strinclusionname &" 'order by gender, student source, total score of the College Entrance Examination
* Go to the telephone fee statistics of each unit from the database for one year (two sources of fixed telephone fee congratulation fertilizer List)
Select a. userper, a. tel, a. standalone, TO_CHAR (a. telfeedate, 'yyyy') AS telyear,
SUM (decode (TO_CHAR (a. telfeedate, 'mm'), '01', a. factration) as jan,
SUM (decode (TO_CHAR (a. telfeedate, 'mm'), '02', a. factration) as fri,
SUM (decode (TO_CHAR (a. telfeedate, 'mm'), '03', a. factration) as mar,
SUM (decode (TO_CHAR (a. telfeedate, 'mm'), '04 ', a. factration) as apr,
SUM (decode (TO_CHAR (a. telfeedate, 'mm'), '05 ', a. factration) as may,
SUM (decode (TO_CHAR (a. telfeedate, 'mm'), '06', a. factration) as jue,
SUM (decode (TO_CHAR (a. telfeedate, 'mm'), '07 ', a. factration) as jul,
SUM (decode (TO_CHAR (a. telfeedate, 'mm'), '08 ', a. factration) as agu,
SUM (decode (TO_CHAR (a. telfeedate, 'mm'), '09', a. factration) as sep,
SUM (decode (TO_CHAR (a. telfeedate, 'mm'), '10', a. factration) as oct,
SUM (decode (TO_CHAR (a. telfeedate, 'mm'), '11', a. factration) as nov,
SUM (decode (TO_CHAR (a. telfeedate, 'mm'), '12', a. factration) AS DEC
FROM (Select a. userper, a. tel, a. standalone, B. telfeedate, B. factration
From telfeestand a, telstmb
Where a. tel = B. telfax)
Group by a. userper, a. tel, a. standalone, TO_CHAR (a. telfeedate, 'yyyy ')
* Note: Four-table join query Problems
Select * from a left inner join B on. a = B. B right inner join c on. a = c. c inner join d on. a = d. d where .....
* Note: Obtain the smallest unused ID number in the table.
* Select (case when exists (Select * FROM Handle B Where B. handleID = 1) then min (HandleID) + 1 ELSE 1 END) as HandleID FROM Handle Where NOT HandleID IN (Select. handleID-1 FROM Handle)
* A problem with an SQL statement: column and column Conversion
Select * from v_temp
The preceding view result is as follows:
User_name role_name
-------------------------
System Administrator
Feng Administrator
Feng users
Test Users
The result is as follows:
User_name role_name
---------------------------
System Administrator
Feng administrator, general user
Test Users
==============================
Create table a_test (name varchar (20), role2 varchar (20 ))
Insert into a_test values ('lil', 'admin ')
Insert into a_test values ('zhang', 'admin ')
Insert into a_test values ('zhang', 'average user ')
Insert into a_test values ('change', 'General user ')
Create function join_str (@ content varchar (100 ))
Returns varchar (2000)
As
Begin
Declare @ str varchar (2000)
Set @ str =''
Select @ str = @ str + ',' + rtrim (role2) from a_test where [name] = @ content
Select @ str = right (@ str, len (@ str)-1)
Return @ str
End
Go
-- Call:
Select [name], DBO. join_str ([name]) role2 from a_test group by [name]
-- Select distinct name, DBO. uf_test (name) from a_test
* Quickly compare two tables with the same structure
For two tables with the same structure, one table has about 30 thousand records and one table has about 20 thousand records. How can I quickly find different records of the two tables?
======================================
Here is a test method for getting data from the orders table in northwind.
Select * into N1 from orders
Select * into N2 from orders
Select * from N1
Select * from n2
-- Add a primary key and modify several entries of several fields in n1.
Alter table n1 add constraint pk_n1_id primary key (OrderID)
Alter table n2 add constraint pk_n2_id primary key (OrderID)
Select OrderID from (select * from n1 union select * from n2) a group by OrderID having count (*)> 1
Yes, and the IDs of different records are displayed.
The following applies to situations where both parties record the same,
Select * from n1 where orderid in (select OrderID from (select * from n1 union select * from n2) a group by OrderID having count (*)> 1)
Records that do not exist between the two parties are better handled.
-- Delete several records in n1 and n2
Delete from n1 where orderID in ('20140901', '20160901 ')
Delete from n2 where orderID in ('20140901', '20160901 ')
--*************************************** **********************
-- Both parties have this record but are not exactly the same
Select * from n1 where orderid in (select OrderID from (select * from n1 union select * from n2) a group by OrderID having count (*)> 1)
Union
-- If n2 exists but does not exist in n1, it is stored in, limit 30.
Select * from n1 where OrderID not in (select OrderID from n2)
Union
-- N1.
Select * from n2 where OrderID not in (select OrderID from n1)
* Four methods to obtain n to m records in the table:
1.
Select top m * into temporary table (or table variable) from tablename order by columnname -- insert top m pen
Set rowcount n
Select * from Table variable order by columnname desc
2.
Select top n * from (select top m * from tablename order by columnname) a order by columnname desc
3. If there are no other identity columns in tablename, then:
Select identity (int) id0, * into # temp from tablename
N to m statements:
Select * from # temp where id0> = n and id0 <= m
If you report an error when executing the select identity (int) id0, * into # temp from tablename statement, this is because the select into/bulkcopy attribute in the middle of your DB is not enabled and must be executed first:
Exec sp_dboption your DB name, 'select into/bulkcopy', true
4. If the table contains the identity attribute, it is simple:
Select * from tablename where identitycol between n and m
* How do I delete repeated records in a table?
Create table a_dist (id int, name varchar (20 ))
Insert into a_dist values (1, 'abc ')
Insert into a_dist values (1, 'abc ')
Insert into a_dist values (1, 'abc ')
Insert into a_dist values (1, 'abc ')
Exec up_distinct 'A _ dist', 'id'
Select * From a_dist
Create procedure up_distinct (@ t_name varchar (30), @ f_key varchar (30 ))
-- F_key indicates the group field, that is, the primary key field.
As
Begin
Declare @ max integer, @ id varchar (30), @ SQL varchar (7999), @ type integer
Select @ SQL = 'maid cur_rows cursor for select' + @ f_key + ', count (*) from '+ @ t_name + 'group by' + @ f_key + 'having count (*)> 1'
Exec (@ SQL)
Open cur_rows
Fetch cur_rows into @ id, @ max
While @ fetch_status = 0
Begin
Select @ max = @ max-1
Set rowcount @ max
Select @ type = xtype from syscolumns where id = object_id (@ t_name) and name = @ f_key
If @ type = 56
Select @ SQL = 'delete from' + @ t_name + 'where' + @ f_key + '=' + @ ID
If @ type = 167
Select @ SQL = 'delete from' + @ t_name + 'where' + @ f_key + '=' + ''' + @ ID + ''''
Exec (@ SQL)
Fetch cur_rows into @ ID, @ Max
End
Close cur_rows
Deallocate cur_rows
Set rowcount 0
End
Select * From policypes
Select * From syscolumns where id = object_id ('A _ dist ')
* Maximum sorting of queried data (only one statement can be used for writing)
Create Table hard (qu char (11), Co char (11), je numeric (3, 0 ))
Insert into hard values ('A', '1', 3)
Insert into hard values ('A', '2', 4)
Insert into hard values ('A', '4', 2)
Insert into hard values ('A', '6', 9)
Insert into hard values ('B', '1', 4)
Insert into hard values ('B', '2', 5)
Insert into hard values ('B', '3', 6)
Insert into hard values ('C', '3', 4)
Insert into hard values ('C', '6', 7)
Insert into hard values ('C', '2', 3)
The query results are as follows:
Qu co je
---------------------------
A 6 9
A 2 4
B 3 6
B 2 5
C 6 7
C 3 4
Group by qu. In each group, the first two digits of je are the largest !!
Only one SQL statement can be used !!!
Select * from hard a where je in (select top 2 je from hard B where a. qu = B. qu order by je)
* Is the SQL statement used to delete Repeated Records?
How to delete a record with the same field, leaving only one record.
For example, the table test contains the id and name fields.
If there are records with the same name, only one record is left, and the remaining records are deleted.
The content of the name is not fixed, and the number of identical records is not fixed.
Is there such an SQL statement?
====================================
A: A complete solution:
Record duplicate records in the temp1 table:
Select [flag field id], count (*) into temp1 from [Table name]
Group by [flag field id]
Having count (*)> 1
2. Record non-Repeated Records in Table temp1:
Insert temp1 select [flag field ID], count (*) from [Table name] group by [flag field ID] Having count (*) = 1
3. Create a table that contains all non-Repeated Records:
Select * into temp2 from [Table name] where flag field ID in (select flag field ID from temp1)
4. Delete duplicate tables:
Delete [Table name]
5. Restore table:
Insert [Table name] Select * From temp2
6. delete a temporary table:
Drop table temp1
Drop table temp2
======================================
B:
Create table a_dist (id int, name varchar (20 ))
Insert into a_dist values (1, 'abc ')
Insert into a_dist values (1, 'abc ')
Insert into a_dist values (1, 'abc ')
Insert into a_dist values (1, 'abc ')
Exec up_distinct 'A _ dist', 'id'
Select * from a_dist
Create procedure up_distinct (@ t_name varchar (30), @ f_key varchar (30 ))
-- F_key indicates the group field, that is, the primary key field.
As
Begin
Declare @ max integer, @ id varchar (30), @ SQL varchar (7999), @ type integer
Select @ SQL = 'maid cur_rows cursor for select' + @ f_key + ', count (*) from '+ @ t_name + 'group by' + @ f_key + 'having count (*)> 1'
Exec (@ SQL)
Open cur_rows
Fetch cur_rows into @ id, @ max
While @ fetch_status = 0
Begin
Select @ max = @ max-1
Set rowcount @ max
Select @ type = xtype from syscolumns where id = object_id (@ t_name) and name = @ f_key
If @ type = 56
Select @ SQL = 'delete from' + @ t_name + 'where' + @ f_key + '=' + @ id
If @ type = 167
Select @ SQL = 'delete from' + @ t_name + 'where' + @ f_key + '=' + ''' + @ id + ''''
Exec (@ SQL)
Fetch cur_rows into @ id, @ max
End
Close cur_rows
Deallocate cur_rows
Set rowcount 0
End
Select * from policypes
Select * from syscolumns where id = object_id ('A _ dist ')
* Column/column conversion-common
Assume that there is a student summary table (CJ) as follows:
Name Subject Result
Zhang San Chinese 80
Zhang San, mathematics 90
Zhang San physical 85
Li Si Chinese 85
Li Si mathematics 92
Li Si physical 82
Want to become
Name, Chinese, Mathematics, Physics
Zhang San 80 90 85
Li Si 85 92 82
Declare @ SQL varchar (4000)
Set @ SQL = 'select name'
Select @ SQL = @ SQL + ', sum (case Subject when ''' + Subject + ''' then Result end) [' + Subject + ']'
From (select distinct Subject from CJ) as
Select @ SQL = @ SQL + 'from test group by name'
Exec (@ SQL)
Column and column conversion-Merge
Table,
Id pid
1 1
1 2
1 3
2 1
2 2
3 1
How to convert Table B:
Id pid
1 1, 2, 3
2 1, 2
3 1
Create a merged Function
Create function fmerg (@ id int)
Returns varchar (8000)
As
Begin
Declare @ str varchar (8000)
Set @ str =''
Select @ str = @ str + ',' + cast (pid as varchar) from Table A where id = @ id
Set @ str = right (@ str, len (@ str)-1)
Return (@ str)
End
Go
-- Call the custom function to obtain the result.
Select distinct id, dbo. fmerg (id) from Table
* How to obtain all column names of a data table
The method is as follows: first obtain the SYSTEMID of the data table from the SYSTEMOBJECT system table, and then retrieve all the column names of the data table from the SYSCOLUMN table.
The SQL statement is as follows:
Declare @ objid int, @ objname char (40)
Set @ objname = 'tablename'
Select @ objid = id from sysobjects where id = object_id (@ objname)
Select 'column _ name' = name from syscolumns where id = @ objid order by colid
Or
Select * FROM INFORMATION_SCHEMA.COLUMNS Where TABLE_NAME = 'users'
* Use SQL statements to change the User Password
Sysadmin role is required to modify other users.
Exec sp_password null, 'newpassword', 'user'
If the account is Sa, execute exec sp_password null, 'newpassword', SA
* How can I determine which fields in a table cannot be blank?
Select column_name from information_schema.columns where is_nullable = 'no' and table_name = tablename
* How can I find a table with the same fields in the database?
A. query the names of known Columns
Select B. Name as tablename, A. Name as columnname
From syscolumns a inner join sysobjects B
On a. ID = B. ID
AND B. type = 'U'
AND a. name = 'your field name'
* Query the names of all unknown columns in different tables.
Select o. name As tablename, s1.name As columnname
From syscolumns s1, sysobjects o
Where s1.id = o. id
And o. type = 'U'
And Exists (
Select 1 From syscolumns s2
Where s1.name = s2.name
And s1.id <> s2.id
)
* Query row xxx data
Assume that id is the primary key:
Select * from (select top xxx * from yourtable) aa where not exists (select 1 from (select top XXX-1 * from yourtable) bb where aa. id = bb. id)
You can also use a cursor.
Fetch absolute [number] from [cursor_name]
The number of rows is absolute.
* SQL Server date calculation
A. the first day of a month
Select DATEADD (mm, DATEDIFF (mm, 0, getdate (), 0)
B. Monday of the week
Select dateadd (wk, datediff (wk, 0, getdate (), 0)
C. The first day of a year
Select dateadd (YY, datediff (YY, 0, getdate (), 0)
D. The first day of the quarter
Select dateadd (QQ, datediff (QQ, 0, getdate (), 0)
E. Last day of last month
Select dateadd (MS,-3, dateadd (mm, datediff (mm, 0, getdate (), 0 ))
F. Last day of last year
Select dateadd (MS,-3, dateadd (YY, datediff (YY, 0, getdate (), 0 ))
G. Last day of the month
Select dateadd (MS,-3, dateadd (mm, datediff (M, 0, getdate () + 1, 0 ))
H. The first Monday of this month
Select dateadd (wk, datediff (wk, 0,
Dateadd (DD, 6-datepart (day, getdate (), getdate ())
), 0)
I. The last day of the year
Select dateadd (MS,-3, dateadd