First, the basic
1, Description: Create Database
CREATE DATABASE database-name
2, Description: delete the database
drop database database name
3, Description: backup sql server
- Create a backup data device
USE master
EXEC sp_addumpdevice ‘disk’, ‘testBack’, ‘c:\mssql7backup\MyNwind_1.dat’
- Start Backup
BACKUP DATABASE pubs TO testBack
4, Description: create a new table
create table 表名 (列名 数据类型 primary key(设置主键)
列名 数据类型
列名 数据类型 not null(不能设置空值))
Create a new table based on existing table:
A: create table tab_new like tab_old (using the old table to create a new table)
B:create table tab_new as select col1,col2… from tab_old definition only
5, Description: Delete the new table
drop table tabname
6. Description: Add a column
Alter table tabname add column col type
Note: The column can not be deleted after the increase. After adding DB2 column data types can not change, the only change is to increase the length of varchar type.
7, description: add the primary key: Alter table tabname add primary key (col)
Description: Remove the primary key: Alter table tabname drop primary key (col)
8, Description: Create index: create [unique] index idxname on tabname (col ....)
Delete Index: drop index idxname
Note: The index is not changed, want to change must be deleted to re-build.
9, Description: Create view: create view viewname as select statement
Delete view: drop view viewname
10, Description: a few simple basic sql statement
Select: select * from table1 where scope
插入:insert into table1(field1,field2) values(value1,value2)
Delete: delete from table1 where the scope of
Update: update table1 set field1 = value1 where the range
Find: select * from table1 where field1 like '% value1%' -like syntax is very subtle, to find information!
排序:select * from table1 order by field1,field2 [desc]
总数:select count as totalcount from table1
求和:select sum(field1) as sumvalue from table1
平均:select avg(field1) as avgvalue from table1
最大:select max(field1) as maxvalue from table1
最小:select min(field1) as minvalue from table1
11, Description: several high-level query term operation
A: UNION operator
UNION operator derives a result table by combining the results of the other two tables (e.g. TABLE1 and TABLE2) and eliminate any duplicate rows. When used in conjunction with ALL UNION (i.e. UNION ALL), not eliminate duplicate rows. In both cases, each row of the derived table is not from TABLE1 from TABLE2.
B: EXCEPT Operator
EXCEPT operator by including all the rows in TABLE2 TABLE1 but not in the elimination of all duplicate rows and derive a result table. When used in conjunction with ALL EXCEPT (EXCEPT ALL), not eliminate duplicate rows.
C: INTERSECT operator
INTERSECT operator by including only TABLE1 and TABLE2 both rows and eliminate all duplicate rows derives a result table. When used in conjunction with ALL INTERSECT (INTERSECT ALL), not eliminate duplicate rows.
Note: Use the operation of several query results word line must be the same.
12, Description: using outer joins
A、left (outer) join:
Left outer join (left join): The result set includes matching row of the connection table, all rows include a left connection table.
SQL: select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c
B:right (outer) join:
Right outer join (right link): The result set includes both a mating connector connection table row, all rows include a right connection table.
C:full/cross (outer) join:
Full outer join: not only match the symbolic link table rows, further comprising two connecting all records in the table.
12, groups: Group by:
A table, once the group is complete, the inquiry can only get information related to the group.
Group statistics) count, sum, max, min, standards-related information packet :( avg)
When the packet SQLServer: can not be text, ntext, image type field of the grouping
In selecte statistical functions in the field, and not an ordinary field together;
13, the database operations:
Detach the database: sp_detach_db; additional database: sp_attach_db then after show, complete additional required pathname
14. How do you change the name of the database:
sp_renamedb ‘old_name’, ‘new_name’
Second, to enhance
1, Description: Copy table (only replicated structure, source table names: a new table name: b) (Access available)
Method a: select * into b from a where 1 <> 1 (only for SQlServer)
法二:select top 0 * into b from a
2, Description: copy table (copy the data source table name: a target table name: b) (Access available)
insert into b(a, b, c) select d,e,f from b;
3, description: copying between cross database table (specific data using an absolute path) (Access available)
insert into b (a, b, c) select d, e, f from b in 'specific database' where conditions
例子:…from b in ‘"&Server.MapPath(".")&"\data.mdb" &"’ where…
4, description: subqueries (table 1: a table name 2: b)
select a,b,c from a where a IN (select d from b ) 或者: select a,b,c from a where a IN (1,2,3)
5, Description: display the article, the author and the final response time
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b
6, description: outer join query (table 1: a table 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
7, Description: Online view query (table name 1: a)
select * from (SELECT a,b,c FROM a) T where t.a > 1;
8, description: between usage, including the boundary values between limit the scope of the query data, not between not included
select * from table1 where time between time1 and time2
select a,b,c, from table1 where a not between 数值1 and 数值2
9, explanation: in the use
select * from table1 where a [not] in ( 'value 1', 'value 2', '4 value', 'value 6')
10, Description: Two related tables, delete the main table has no information on side tables
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )
11, Description: Four tables joint investigation questions:
select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where …
12, Description: five minutes ahead of schedule reminder
SQL: select * from schedule where datediff ( 'minute', f start time, getdate ())> 5
13, Description: a database sql statement buttoned page
select top 10 b. * from (select top 20 primary key field, sort field from table order by sort field desc) a, table b where b. The primary key field = a. primary key field order by a. sort field
Implementation:
About database page:
declare @start int,@end int
@sql nvarchar(600)
set @sql=’select top’+str(@end-@start+1)+’+from T where rid not in(select top’+str(@str-1)+’Rid from T where Rid>-1)’
exec sp_executesql @sql
Note: You can not with a variable, so the only way of special treatment in practical applications directly after the top. Rid is an identity column, if there are specific top field, this is very good. Because inconsistent avoid the top field if logical index, the query results in the actual table (data in the logical index and possible inconsistencies in the data table, while the index in the first query, if the query index)
14, description: the first 10 rows
select top 10 * form table1 where the range
15, Description: select a maximum recording all the information corresponding to the same b-value data in each group (like this forum for a monthly usage can list, monthly selling product analysis, performance ranking by subject, and many more.)
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)
16, description: including but not all in TableA TableB TableC rows and remove all duplicate rows and derive a result table
(select a from tableA ) except (select a from tableB) except (select a from tableC)
17, Description: Remove 10 random data
select top 10 * from tablename order by newid()
18, Description: randomly selected records
select change ()
19, Description: Delete duplicate records
1),delete from tablename where id not in (select max(id) from tablename group by col1,col2,…)
2),select distinct * into temp from tablename
delete from tablename
insert into tablename select * from temp
Evaluation: This operation moving large amounts of data involved, this approach is not suitable for large-capacity data operation but
3), for example: import data in an external table, for some reason, only the first introduction part, it is difficult to determine the specific location, so that only the next introduced all at once, so that it generates a lot of repeated fields, how to remove repeat field
alter table tablename
- Add a auto-increment
add column_b int identity(1,1)
delete from tablename where column_b not in(
select max(column_b) from tablename group by column1,column2,…)
alter table tablename drop column column_b
20, Description: list all table names in the database
// U representative of select name from sysobjects where type = 'U' user
21, Description: list all table column names of
select name from syscolumns where id=object_id(‘TableName’)
22, description: listed type, vender, pcs field to field type arrangement, case can easily achieve multiple choice, select the similar case.
select type,sum(case vender when ‘A’ then pcs else 0 end),sum(case vender when ‘C’ then pcs else 0 end),sum(case vender when ‘B’ then pcs else 0 end) FROM tablename group by type
Show results:
type vender pcs
A 1 computer
A 1 computer
Disc B 2
A 2 CD
B 3 mobile phones
C 3 phones
23, Description: Initialize the table table1
TRUNCATE TABLE table1
24, Description: Select record from 10 to 15
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc
Third, skills
1,1 = 1,1 = 2 is used, when used in SQL statements more
"Where 1 = 1" is a Select All "where 1 = 2" are not all selected,
Such as:
if @strWhere !=’’
begin
set @strSQL = ‘select count(*) as Total from [’ + @tblName + '] where ’ + @strWhere
end
else
begin
set @strSQL = ‘select count(*) as Total from [’ + @tblName + ‘]’
end
We can directly write
Error! Contents entries found.
set @strSQL = 'select count (*) as Total from [' + @tblName + '] where 1 = 1 stable' + @strWhere 2, shrink the database
- rebuild the index
DBCC REINDEX
DBCC INDEXDEFRAG
- shrink data and log
DBCC SHRINKDB
DBCC SHRINKFILE
3, compressed database
dbcc shrinkdatabase(dbname)
4, transfer the database to the new user to existing user rights
exec sp_change_users_login ‘update_one’,‘newname’,‘oldname’
go
5, the backup check set
RESTORE VERIFYONLY from disk=‘E:\dvbbs.bak’
6, repair database
ALTER DATABASE [dvbbs] SET SINGLE_USER
GO
DBCC CHECKDB(‘dvbbs’,repair_allow_data_loss) WITH TABLOCK
GO
ALTER DATABASE [dvbbs] SET MULTI_USER
GO
7, log cleared
SET NOCOUNT ON
DECLARE @LogicalFileName sysname,
@MaxMinutes INT,
@NewSize INT
USE tablename - the database name to be operated
SELECT @LogicalFileName = 'tablename_log', - log file name
@MaxMinutes = 10, – Limit on time allowed to wrap log.
@NewSize = 1 - the size you want to set the log file (M)
Setup / initialize
DECLARE @OriginalSize int
SELECT @OriginalSize = size
FROM sysfiles
WHERE name = @LogicalFileName
SELECT 'Original Size of ’ + db_name() + ’ LOG is ’ +
CONVERT(VARCHAR(30),@OriginalSize) + ’ 8K pages or ’ +
CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + ‘MB’
FROM sysfiles
WHERE name = @LogicalFileName
CREATE TABLE DummyTrans
(DummyColumn char (8000) not null)
DECLARE @Counter INT,
@StartTime DATETIME,
@TruncLog VARCHAR(255)
SELECT @StartTime = GETDATE(),
@TruncLog = ‘BACKUP LOG ’ + db_name() + ’ WITH TRUNCATE_ONLY’
DBCC SHRINKFILE (@LogicalFileName, @NewSize)
EXEC (@TruncLog)
– Wrap the log if necessary.
WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) – time has not expired
AND @OriginalSize = (SELECT size FROM sysfiles WHERE name = @LogicalFileName)
AND (@OriginalSize * 8 /1024) > @NewSize
BEGIN – Outer loop.
SELECT @Counter = 0
WHILE ((@Counter < @OriginalSize / 16) AND (@Counter < 50000))
BEGIN – update
INSERT DummyTrans VALUES ( 'Fill Log') DELETE DummyTrans
SELECT @Counter = @Counter + 1
END
EXEC (@TruncLog)
END
SELECT 'Final Size of ’ + db_name() + ’ LOG is ’ +
CONVERT(VARCHAR(30),size) + ’ 8K pages or ’ +
CONVERT(VARCHAR(30),(size*8/1024)) + ‘MB’
FROM sysfiles
WHERE name = @LogicalFileName
DROP TABLE DummyTrans
SET NOCOUNT OFF
8, Description: Changing a table
exec sp_changeobjectowner ‘tablename’,‘dbo’
9, all table storage changes
CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch
@OldOwner as NVARCHAR(128),
@NewOwner as NVARCHAR(128)
AS
DECLARE @Name as NVARCHAR(128)
DECLARE @Owner as NVARCHAR(128)
DECLARE @OwnerName as NVARCHAR(128)
DECLARE curObject CURSOR FOR
select ‘Name’ = name,
‘Owner’ = user_name(uid)
from sysobjects
where user_name(uid)=@OldOwner
order by name
OPEN curObject
FETCH NEXT FROM curObject INTO @Name, @Owner
WHILE(@@FETCH_STATUS=0)
BEGIN
if @Owner=@OldOwner
begin
set @OwnerName = @OldOwner + ‘.’ + rtrim(@Name)
exec sp_changeobjectowner @OwnerName, @NewOwner
end
– select @name,@NewOwner,@OldOwner
FETCH NEXT FROM curObject INTO @Name, @Owner
END
close curObject
deallocate curObject
GO
10, SQL SERVER cycle write data directly
declare @i int
set @i=1
while @i<30
begin
insert into test (userid) values(@i)
set @i=@i+1
end