Complete collection of classic SQL statements

WBOY
Release: 2016-08-08 09:28:58
Original
1162 people have browsed it

1. Basics

1, Description: Create database
CREATE DATABASE database-name
2, Description: Delete database
drop database dbname
3, Description: Backup sql server
--- Create device
USE master
EXEC sp_addumpdevice 'disk', 'testBack', 'c:mssql7backupMyNwind_1.dat'
--- Start backup

BACKUP DATABASE pubs TO testBack
4、Instructions: Create a new table
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)

Create a new table based on an existing table:
A: create table tab_new like tab_old (use 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 new table
drop table tabname
6, Description: Add a column
Alter table tabname add column col type
Note: After adding a column, it cannot be deleted. In DB2, the data type cannot be changed after the column is added. The only thing that can be changed is to increase the length of the varchar type.
7. Instructions: Add primary key: Alter table tabname add primary key(col)
Instructions: Delete primary key: Alter table tabname drop primary key(col)

8. Instructions: Create index: create [unique] index idxname on tabname(col….)
Delete index: drop index idxname

Note: The index cannot be changed. If you want to change it, you must delete it and rebuild it.
9, Description: Create a view: create view viewname as select statement
Delete view: drop view viewname
10, Description: A few simple basic sql statements
Select: select * from table1 where range
insert: insert into table1(field1,field2) values(value1,value2)
delete: delete from table1 where range

update: ​​update table1 set field1= value1 where range
Search: select * from table1 where field1 like '%value1%' ---likeThe syntax is very exquisite, check the information!
Sort: select * from table1 order by field1,field2 [desc]
Total:
select count as totalcount from table1
Sum:
select sum(field1) as sumvalue from table1
Average:
select avg(field1) as avgvalue from table1
Max:
select max(field1) as maxvalue from table1
minimum:
select min(field1) as minvalue from table1
11, description: several advanced query operation words
A: UNION Operators The
UNION operator derives a result table by combining two other result tables (such as TABLE1 and TABLE2) and eliminating any duplicate rows in the tables. When ALL is used with UNION (that is, UNION ALL), duplicate rows are not eliminated. In both cases, each row of the derived table comes from either TABLE1 or TABLE2
.
B: EXCEPT operator
EXCEPT operator derives a result table by including all rows that are in TABLE1 but not in TABLE2 and eliminating all duplicate rows. When ALL is used with EXCEPT (EXCEPT ALL), duplicate rows are not eliminated.
C: INTERSECT operator
INTERSECT operator derives a result table by including only rows that are present in both TABLE1 and TABLE2 and eliminating any duplicate rows. When ALL is used with INTERSECT (INTERSECT ALL), duplicate rows are not eliminated.
Note: Several query result lines using operator words must be consistent .
12
, description: Use outer join
A, left (outer) join:
left
Outer join (left join): The result set includes matching rows of the joined table, as well as Left joins all rows of the 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 join): result The set includes both matching join rows from the join table and all rows from the right join table.
C: full/cross (outer) join:
Full outer join: not only includes matching rows of the symbolic connection table, but also includes all records in the two connected tables.
12, grouping:Group by:
​​
A table, once the grouping is completed, only group-related information can be obtained after querying.
Group related information: (statistical information) count, sum, max, min, avg Criteria for grouping )
When grouping in SQL Server: Fields of text, ntext, and image types cannot be used as the grouping basis
The fields in the selecte statistical function cannot be placed together with ordinary fields;

13, operate the database:
Detach the database: sp_detach_db; Attach the database : sp_attach_db followed by indicates that attachment requires a complete path name
14. How to modify the database Name:
sp_renamedb 'old_name', 'new_name'

2. Improvement

1, Description: Copy table (only copy structure, source table name: a New table name: b) (Access available)
Method 1: select * into b from a where 1<> ;1 (only for SQlServer)
Method 2: select top 0 * into b from a
2, description: copy table (copy 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: Copy tables between databases (use absolute paths for specific data) (Access available)
insert into b(a, b, c) select d,e,f from b in 'Specific database' where condition
Example: ..from b in '"&Server.MapPath(".")&"data.mdb" &"' where..

4, description: subquery (table name 1: a table name 2: b)
select a,b,c from a where a IN (select d from b) or: select a,b ,c from a where a IN (1,2,3)

5, Description: Display 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

6, description: outer join query (table name 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: usage of between, between limits the query data range and includes boundary values, not between does not include
select * from table1 where time between time1 and time2
select a,b,c, from table1 where a not between value 1 and value 2

9、Instructions: How to use in
select * from table1 where a [not] in ('value1','value2','value4','value6')

10, Description: Two related tables, delete the information in the main table that is not in the secondary table
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )

11、Explanation: Four table joint query problem:
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: Schedule reminder five minutes in advance
SQL: select * from Schedule where datediff('minute',f start time,getdate())>5

13, description: One sql statement to complete database paging
select top 10 b.* from (select top 20 primary key field,sort field from table nameorder by sort fielddesc) a,Table name b where b.Primary key field = a.Primary key field order by a.Sort field
Specific implementation:
About database paging:

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: top cannot be directly followed by a variable, so in practical applications this is the only way to perform special processing. Rid is an identification column. If there are specific fields after top, this is very beneficial. Because this can avoid the inconsistency in the actual table after the query result if the top field is a logical index (the data in the logical index may be inconsistent with the data table, and if it is in the index during the query, the index will be queried first)

14, description: top 10 records
select top 10 * form table1 where range

15, description: Select all the information of the record with the largest a corresponding to each group of data with the same b value (similar usage can be used for monthly forum rankings, monthly hot-selling product analysis, press Subject score ranking, etc..)
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)

16. Description: Include all rows in TableA but not in TableB and TableC and eliminate all duplicate rows to derive a result table
(select a from tableA) except (select a from tableB) except ( select a from tableC)

17、Instructions: Randomly take out 10 pieces of data
select top 10 * from tablename order by newid()

18, Description: Randomly select records
select newid()

19、Explanation: 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 involves the movement of a large amount of data. This approach is not suitable for large volumes but Data operation
3), for example: importing data into an external table, for some reasons only a part of it is imported the first time, but it is difficult to judge the specific location, so only the whole thing is imported next time, which creates a lot of duplication fields, how to delete duplicate fields

alter table tablename
--
Add an auto-increment column
add column_bint 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
select name from sysobjects where type='U' // U represents user

21, Description: List all column names in the table
select name from syscolumns where id=object_id('TableName')

22. Description: List the type, vendor, and pcs fields, arranged by the type field. Case can easily implement multiple selections, similar to the case in select.
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
Display results:
type vender pcs
ComputerA 1
Computer
A 1
CD
B 2
CD
A 2
Mobile phone
B 3
Mobile phone C 3

23. Description: Initialize table table1

TRUNCATE TABLE table1

24, Description: Select records from 10 to 15
select top 5 * from (select top 15 * from table order by id asc) table_alias order by id desc

3. Skills

1, 1=1, 1=2 are often used in SQL statement combinations

"where 1=1" means to select all "where 1=2" and not select all,
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 write it directly as

Error! Catalog entry not found.
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1 stabilize '+ @strWhere 2, shrink the database
--Rebuild the index
DBCC REINDEX
DBCC INDEXDEFRAG
--
Shrink data and logs
DBCC SHRINKDB
DBCC SHRINKFILE

3, compress database
dbcc shrinkdatabase(dbname)

4, transfer the database to the new user with existing user rights
exec sp_change_users_login 'update_one','newname','oldname'
go

5、Check the backup 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 clear
SET NOCOUNT ON
DECLARE @LogicalFileName sysname,
@MaxMinutes INT,
@NewSize INT


USE tablename -- The name of the database to be operated
SELECT @LogicalFileName = 'tablename_log', -- Log file name
@MaxMinutes = 10, -- Limit on time allowed to wrap log.
@NewSize = 1 --
The size of the log file you want to set (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: Change a table
exec sp_changeobjectowner 'tablename','dbo'

9. Store changes to all tables

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, write data directly in SQL SERVER loop
declare @i int
set @i=1
while @i<30
begin
insert into test (userid) values(@i)
set @i=@i+1
end
Case
:
has the following table. It is required to correct all the failing grades and make them just pass on the basis of an increase of 0.1 each time:

Name Score

Zhangshan 80

Lishi 59

Wangwu 50

Songquan 69

while((select min(score) from tb_table)<60)

begin

update tb_table set score =score*1.01

where score<60

if (select min(score) from tb_table)>60

break

else

Continue

end

Data Development-Classic


1. Sort by strokes of last name:
Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as //From least to most

2. Database encryption:
select encrypt('original password')
select pwdencrypt('original password
')
select pwdcompare('original password','encrypted password') = 1 --Same; otherwise not the same encrypt('original password
')
select pwdencrypt('original password
')
select pwdcompare('original password','encrypted password') = 1--same; otherwise not Same

3.Retrieve the fields in the table:
declare @list varchar(1000),
@sql nvarchar(1000)
select @list=@list+','+b.name from sysobjects a, syscolumns b where a.id=b.id and a.name='
TableA'
set @sql='select '+right(@list,len(@list)-1)+' from Table A'
exec (@sql)

4.View hard disk partition:
EXEC master..xp_fixeddrives

5.Compare tables A and B for equality:
if (select checksum_agg(binary_checksum(*)) from A)
=
(select checksum_agg(binary_checksum(*)) from B)
print '
Equal'
else
print 'Not equal'

6.Kill all profiler processes:
DECLARE hcforeach CURSOR GLOBAL FOR SELECT 'kill '+RTRIM(spid) FROM master.dbo.sysprocesses
WHERE program_name IN('SQL profiler', N'SQL
Profiler')
EXEC sp_msforeach_worker '?
'

7.Record search:
starting to Nrecords
Select Top N * From table
-------------------------- -----------
N
to M records(must have primary indexID)
Select Top M-N * From tableWhere ID in (Select Top M ID From Table) Order by ID Desc
----------------------------------
NRecord to the end
Select Top N * From TableOrder by ID Desc
Case
For example 1: There are more than 10,000 records in a table. The first field of the table, RecID, is a self-increasing field. Write a SQL statement to find out the value of the table. Records 31 to 40.

select top 10 recid from A where recid not in(select top 30 recid from A)

Analysis: If written like this, some problems will occur if recid has a logical index in the table.

Select top 10 recid from A where... is searched from the index, while the subsequent select top 30 recid from A is searched in the data table, so the order in the index may be inconsistent with that in the data table, which results in What is queried is not the original desired data.

Solution

1. Use order by select top 30 recid from A order by ricid. If the field does not grow automatically, problems will arise

2, Also add conditions to that subquery: select top 30 recid from A where recid>-1

Example2: Query the last record in the table. We don’t know how much data, and table structure there are in this table.
set @s = 'select top 1 * from T where pid not in (select top ' + str(@count-1) + ' pid from T)'

print @s exec sp_executesql @s

9: Get all user tables in the current database
select Name from sysobjects where xtype='u' and status>=0

10: Get all fields of a table
select name from syscolumns where id=object_id('table name')

select name from syscolumns where id in (select id from sysobjects where type = 'u' and name = 'table name')

Both methods have the same effect

11: View views, stored procedures, and functions related to a table
select a.* from sysobjects a, syscomments b where a.id = b.id and b.text like '%table name%'

12: View all stored procedures in the current database
select name as stored procedure name from sysobjects where xtype='P'

13: Query all databases created by the user
select * from master..sysdatabases D where sid not in (select sid from master..syslogins where name='sa')
or
select dbid, name AS DB_NAME from master..sysdatabases where sid <> 0x01

14: Query the fields and data types of a certain table
select column_name,data_type from information_schema.columns
where table_name = 'table name'

15: Data operations between different server databases

--Create a linked server

exec sp_addlinkedserver 'ITSV ', ' ', 'SQLOLEDB ', 'Remote server name or ip address '

exec sp_addlinkedsrvlogin 'ITSV ', 'false ',null, 'username ', 'password '

--Query example

select * from ITSV.database name.dbo.table name

--Import example

select * into table from ITSV.database name.dbo.table name

--Delete linked servers when no longer in use

exec sp_dropserver 'ITSV ', 'droplogins '

--Connect remote/LAN data (openrowset/openquery/opendatasource)

--1. openrowset

--Query example

select * from openrowset( 'SQLOLEDB ', 'sql server name '; 'user name '; 'password ', database name.dbo.table name)

--Generate local table

select * into table from openrowset( 'SQLOLEDB ', 'sql server name '; 'user name '; 'password ', database name.dbo.table name)

--Import local table to remote table

insert openrowset( 'SQLOLEDB ', 'sql server name '; 'user name '; 'password ', database name.dbo.table name)

select *from local table

--Update local table

update b

set b.Column A=a.Column A

from openrowset( 'SQLOLEDB ', 'sql server name '; 'user name '; 'password ', database name.dbo.table name) as a inner join local table b

on a.column1=b.column1

--openquery usage requires creating a connection

--First create a connection to create a linked server

exec sp_addlinkedserver 'ITSV ', ' ', 'SQLOLEDB ', 'Remote server name or ip address '

--Query

select *

FROM openquery(ITSV, 'SELECT * FROM database.dbo.table name ')

--Import local table to remote table

insert openquery(ITSV, 'SELECT * FROM database.dbo.table name ')

select * from local table

--Update local table

update b

set b.Column B=a.Column B

FROM openquery(ITSV, 'SELECT * FROM database.dbo.tablename ') as a

inner join local table b on a.Column A=b.Column A

--3. opendatasource/openrowset

SELECT *

FROM opendatasource( 'SQLOLEDB ', 'Data Source=ip/ServerName;User ID=login name;Password=password ' ).test.dbo.roy_ta

--Import local table to remote table

insert opendatasource( 'SQLOLEDB ', 'Data Source=ip/ServerName;User ID=Login name;Password=Password ').Database.dbo.Table name

select * from local table

SQL Server Basic Functions

SQL Server Basic Functions

1. String function for length and analysis

1,datalength(Char_expr) 返回字符串包含字符数,但不包含后面的空格
2,substring(expression,start,length) 取子串,字符串的下标是从“1”,start为起始位置,length为字符串长度,实际应用中以len(expression)取得其长度
3,right(char_expr,int_expr) 返回字符串右边第int_expr个字符,还用left于之相反
4,isnull( check_expression replacement_value )如果check_expression為空,則返回replacement_value的值,不為空,就返回check_expression字符操作类

5,Sp_addtype 自定義數據類型
例如:EXEC sp_addtype birthday, datetime, 'NULL'

<code><span>6,set nocount {on|off}</span></code>
Copy after login
<span>使返回的结果中不包含有关受 Transact-SQL 语句影响的行数的信息。如果存储过程中包含的一些语句并不返回许多实际的数据,则该设置由于大量减少了网络流量,因此可显著提高性能。SET NOCOUNT 设置是在执行或运行时设置,而不是在分析时设置。</span>
Copy after login
<span>SET NOCOUNT 为 ON 时,不返回计数(表示受 Transact-SQL 语句影响的行数)。</span><br>
<span>SET NOCOUNT </span><span>为 OFF 时,返回计数</span>
Copy after login
<code><span>常识</span></code><code></code>
Copy after login
<code><span> </span></code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
<span><code>在SQL查询中:</code><code>from</code><code>后最多可以跟多少张表或视图:</code><code>256</code><code></code></span>
Copy after login
<span><code>在</code><code>SQL</code><code>语句中出现 </code><code>Order by</code><code>,</code><code>查询时,</code><code>先排序,后取</code></span>
Copy after login
<span><code>在</code><code>SQL</code><code>中,一个字段的最大容量是</code><code>8000</code><code>,而对于</code><code>nvarchar(4000)</code><code>,</code><code>由于</code><code>nvarchar</code><code>是Unicode码。  </code></span>
Copy after login
<code><span>        </span></code>
Copy after login
<code><span>SQLServer2000</span></code><span><code>同步复制技术实现步骤</code><code></code></span>
Copy after login
<code><span>一、 预备工作</span></code><code></code>
Copy after login
<span><code>1.</code><code>发布服务器,订阅服务器都创建一个同名的windows用户,并设置相同的密码,做为发布快照文件夹的有效访问用户</code></span>
Copy after login
<span><code>--</code><code>管理工具</code></span>
Copy after login
<span><code>--</code><code>计算机管理</code></span>
Copy after login
<span><code>--</code><code>用户和组</code></span>
Copy after login
<span><code>--</code><code>右键用户</code></span>
Copy after login
<span><code>--</code><code>新建用户</code></span>
Copy after login
<span><code>--</code><code>建立一个隶属于administrator组的登陆windows的用户(SynUser)</code></span>
Copy after login
<span><code>2.</code><code>在发布服务器上,新建一个共享目录,做为发布的快照文件的存放目录,操作:</code></span>
Copy after login
<code><span>我的电脑--D:\ 新建一个目录,名为: PUB</span></code>
Copy after login
<span><code>--</code><code>右键这个新建的目录</code></span>
Copy after login
<span><code>--</code><code>属性--共享</code></span>
Copy after login
<span><code>--</code><code>选择"共享该文件夹"</code></span>
Copy after login
<span><code>--</code><code>通过"权限"按纽来设置具体的用户权限,保证第一步中创建的用户(SynUser) 具有对该文件夹的所有权限</code></span>
Copy after login
<code><span> </span></code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
<span><code>--</code><code>确定</code></span>
Copy after login
Copy after login
<span><code>3.</code><code>设置SQL代理(SQLSERVERAGENT)服务的启动用户(发布/订阅服务器均做此设置)</code></span>
Copy after login
<code><span>开始--程序--管理工具--服务</span></code>
Copy after login
<span><code>--</code><code>右键SQLSERVERAGENT</code></span>
Copy after login
<span><code>--</code><code>属性--登陆--选择"此账户"</code></span>
Copy after login
<span><code>--</code><code>输入或者选择第一步中创建的windows登录用户名(SynUser)</code></span>
Copy after login
<span><code>--"</code><code>密码"中输入该用户的密码</code></span>
Copy after login
<span><code>4.</code><code>设置SQL Server身份验证模式,解决连接时的权限问题(发布/订阅服务器均做此设置)</code></span>
Copy after login
<code><span>企业管理器</span></code>
Copy after login
Copy after login
<span><code>--</code><code>右键SQL实例--属性</code></span>
Copy after login
<span><code>--</code><code>安全性--身份验证</code></span>
Copy after login
<span><code>--</code><code>选择"SQL Server 和 Windows"</code></span>
Copy after login
<span><code>--</code><code>确定</code></span>
Copy after login
Copy after login
<span><code>5.</code><code>在发布服务器和订阅服务器上互相注册</code></span>
Copy after login
<code><span>企业管理器</span></code>
Copy after login
Copy after login
<span><code>--</code><code>右键SQL Server组</code></span>
Copy after login
<span><code>--</code><code>新建SQL Server注册...</code></span>
Copy after login
<span><code>--</code><code>下一步--可用的服务器中,输入你要注册的远程服务器名 --添加</code></span>
Copy after login
<span><code>--</code><code>下一步--连接使用,选择第二个"SQL Server身份验证"</code></span>
Copy after login
<span><code>--</code><code>下一步--输入用户名和密码(SynUser)</code></span>
Copy after login
<span><code>--</code><code>下一步--选择SQL Server组,也可以创建一个新组</code></span>
Copy after login
<span><code>--</code><code>下一步--完成</code></span>
Copy after login
<span><code>6.</code><code>对于只能用IP,不能用计算机名的,为其注册服务器别名(此步在实施中没用到)</code></span>
Copy after login
<span><code> (</code><code>在连接端配置,比如,在订阅服务器上配置的话,服务器名称中输入的是发布服务器的IP)</code></span>
Copy after login
<code><span>开始--程序--Microsoft SQL Server--客户端网络实用工具</span></code>
Copy after login
<span><code>--</code><code>别名--添加</code></span>
Copy after login
<span><code>--</code><code>网络库选择"tcp/ip"--服务器别名输入SQL服务器名</code></span>
Copy after login
<span><code>--</code><code>连接参数--服务器名称中输入SQL服务器ip地址</code></span>
Copy after login
<span><code>--</code><code>如果你修改了SQL的端口,取消选择"动态决定端口",并输入对应的端口号</code></span>
Copy after login
<code><span>二、 正式配置</span></code><code></code>
Copy after login
<span><code>1</code><code>、配置发布服务器</code></span>
Copy after login
<code><span>打开企业管理器,在发布服务器(B、C、D)上执行以下步骤:</span></code>
Copy after login
<span><code>(1) </code><code>从[工具]下拉菜单的[复制]子菜单中选择[配置发布、订阅服务器和分发]出现配置发布和分发向导 </code></span>
Copy after login
<span><code>(2) [</code><code>下一步] 选择分发服务器 可以选择把发布服务器自己作为分发服务器或者其他sql的服务器(选择自己)</code></span>
Copy after login
<span><code>(3) [</code><code>下一步] 设置快照文件夹</code></span>
Copy after login
<code><span>采用默认\\servername\Pub</span></code>
Copy after login
<span><code>(4) [</code><code>下一步] 自定义配置 </code></span>
Copy after login
<code><span>可以选择:是,让我设置分发数据库属性启用发布服务器或设置发布设置</span></code>
Copy after login
<code><span>否,使用下列默认设置(推荐)</span></code>
Copy after login
<span><code>(5) [</code><code>下一步] 设置分发数据库名称和位置 采用默认值</code></span>
Copy after login
<span><code>(6) [</code><code>下一步] 启用发布服务器 选择作为发布的服务器</code></span>
Copy after login
<span>(7) [下一步] 选择需要发布的数据库和发布类型</span>
Copy after login
<span><code>(8) [</code><code>下一步] 选择注册订阅服务器</code></span>
Copy after login
<span><code>(9) [</code><code>下一步] 完成配置</code></span>
Copy after login
<span><code>2</code><code>、创建出版物</code></span>
Copy after login
<code><span>发布服务器B、C、D上</span></code>
Copy after login
<span><code>(1)</code><code>从[工具]菜单的[复制]子菜单中选择[创建和管理发布]命令</code></span>
Copy after login
<span><code>(2)</code><code>选择要创建出版物的数据库,然后单击[创建发布]</code></span>
Copy after login
<span><code>(3)</code><code>在[创建发布向导]的提示对话框中单击[下一步]系统就会弹出一个对话框。对话框上的内容是复制的三个类型。我们现在选第一个也就是默认的快照发布(其他两个大家可以去看看帮助)</code></span>
Copy after login
<span><code>(4)</code><code>单击[下一步]系统要求指定可以订阅该发布的数据库服务器类型,</code></span>
Copy after login
<span><code>SQLSERVER</code><code>允许在不同的数据库如 orACLE或ACCESS之间进行数据复制。</code></span>
Copy after login
<code><span>但是在这里我们选择运行"SQL SERVER 2000"的数据库服务器</span></code>
Copy after login
<span><code>(5)</code><code>单击[下一步]系统就弹出一个定义文章的对话框也就是选择要出版的表</code></span>
Copy after login
<code><span>注意: 如果前面选择了事务发布 则再这一步中只能选择带有主键的表</span></code>
Copy after login
<span><code>(6)</code><code>选择发布名称和描述</code></span>
Copy after login
<span><code>(7)</code><code>自定义发布属性 向导提供的选择:</code></span>
Copy after login
<code><span>是 我将自定义数据筛选,启用匿名订阅和或其他自定义属性</span></code>
Copy after login
<code><span>否 根据指定方式创建发布 (建议采用自定义的方式)</span></code>
Copy after login
<span><code>(8)[</code><code>下一步] 选择筛选发布的方式 </code></span>
Copy after login
<span><code>(9)[</code><code>下一步] 可以选择是否允许匿名订阅</code></span>
Copy after login
<span><code>1)</code><code>如果选择署名订阅,则需要在发布服务器上添加订阅服务器</code></span>
Copy after login
<code><span>方法: [工具]->[复制]->[配置发布、订阅服务器和分发的属性]->[订阅服务器] 中添加</span></code>
Copy after login
<code><span>否则在订阅服务器上请求订阅时会出现的提示:改发布不允许匿名订阅</span></code>
Copy after login
<code><span>如果仍然需要匿名订阅则用以下解决办法 </span></code>
Copy after login
<span><code>[</code><code>企业管理器]->[复制]->[发布内容]->[属性]->[订阅选项] 选择允许匿名请求订阅</code></span>
Copy after login
<span><code>2)</code><code>如果选择匿名订阅,则配置订阅服务器时不会出现以上提示</code></span>
Copy after login
<span><code>(10)[</code><code>下一步] 设置快照 代理程序调度</code></span>
Copy after login
<span><code>(11)[</code><code>下一步] 完成配置</code></span>
Copy after login
<code><span>当完成出版物的创建后创建出版物的数据库也就变成了一个共享数据库</span></code>
Copy after login
<code><span>有数据 </span></code>
Copy after login
<span><code>srv1.</code><code>库名..author有字段:id,name,phone, </code></span>
Copy after login
<span><code>srv2.</code><code>库名..author有字段:id,name,telphone,adress </code></span>
Copy after login
<code><span> </span></code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
<code><span>要求: </span></code>
Copy after login
<span><code>srv1.</code><code>库名..author增加记录则srv1.库名..author记录增加 </code></span>
Copy after login
<span><code>srv1.</code><code>库名..author的phone字段更新,则srv1.库名..author对应字段telphone更新 </code></span>
Copy after login
<code><span>--*/ </span></code>
Copy after login
<code><span> </span></code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
<span><code>--</code><code>大致的处理步骤 </code></span>
Copy after login
<span><code>--1.</code><code>在 srv1 上创建连接服务器,以便在 srv1 中操作 srv2,实现同步 </code></span>
Copy after login
<span><code>exec sp_addlinkedserver 'srv2','','SQLOLEDB','srv2</code><code>的sql实例名或ip' </code></span>
Copy after login
<span><code>exec sp_addlinkedsrvlogin 'srv2','false',null,'</code><code>用户名','密码' </code></span>
Copy after login
<code><span>go</span></code>
Copy after login
<span><code>--2.</code><code>在 srv1 和 srv2 这两台电脑中,启动 msdtc(分布式事务处理服务),并且设置为自动启动</code></span>
Copy after login
<code><span>。我的电脑--控制面板--管理工具--服务--右键 Distributed Transaction Coordinator--属性--启动--并将启动类型设置为自动启动 </span></code>
Copy after login
<code><span>go </span></code>
Copy after login
<code><span> </span></code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
<code><span> </span></code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
<span><code>--</code><code>然后创建一个作业定时调用上面的同步处理存储过程就行了 </code></span>
Copy after login
<code><span> </span></code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
<code><span>企业管理器 </span></code>
Copy after login
<span><code>--</code><code>管理 </code></span>
Copy after login
<span><code>--SQL Server</code><code>代理 </code></span>
Copy after login
<span><code>--</code><code>右键作业 </code></span>
Copy after login
<span><code>--</code><code>新建作业 </code></span>
Copy after login
<span><code>--"</code><code>常规"项中输入作业名称 </code></span>
Copy after login
<span><code>--"</code><code>步骤"项 </code></span>
Copy after login
<span><code>--</code><code>新建 </code></span>
Copy after login
<span><code>--"</code><code>步骤名"中输入步骤名 </code></span>
Copy after login
<span><code>--"</code><code>类型"中选择"Transact-SQL 脚本(TSQL)" </code></span>
Copy after login
<span><code>--"</code><code>数据库"选择执行命令的数据库 </code></span>
Copy after login
<span><code>--"</code><code>命令"中输入要执行的语句: exec p_process </code></span>
Copy after login
<span><code>--</code><code>确定 </code></span>
Copy after login
<span><code>--"</code><code>调度"项 </code></span>
Copy after login
<span><code>--</code><code>新建调度 </code></span>
Copy after login
<span><code>--"</code><code>名称"中输入调度名称 </code></span>
Copy after login
<span><code>--"</code><code>调度类型"中选择你的作业执行安排 </code></span>
Copy after login
<span><code>--</code><code>如果选择"反复出现" </code></span>
Copy after login
<span><code>--</code><code>点"更改"来设置你的时间安排 </code></span>
Copy after login
<code><span> </span></code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
<code><span> </span></code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
<code><span>然后将SQL Agent服务启动,并设置为自动启动,否则你的作业不会被执行 </span></code>
Copy after login
<code><span> </span></code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
<code><span>设置方法: </span></code>
Copy after login
<code><span>我的电脑--控制面板--管理工具--服务--右键 SQLSERVERAGENT--属性--启动类型--选择"自动启动"--确定. </span></code>
Copy after login
<code><span> </span></code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
<code><span> </span></code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
<span><code>--3.</code><code>实现同步处理的方法2,定时同步 </code></span>
Copy after login
<code><span> </span></code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
<span><code>--</code><code>在srv1中创建如下的同步处理存储过程 </code></span>
Copy after login
<code><span>create proc p_process </span></code>
Copy after login
<code><span>as </span></code>
Copy after login
<span><code>--</code><code>更新修改过的数据 </code></span>
Copy after login
<code><span>update b set name=i.name,telphone=i.telphone </span></code>
Copy after login
<span><code>from srv2.</code><code>库名.dbo.author b,author i </code></span>
Copy after login
<code><span>where b.id=i.id and</span></code>
Copy after login
<code><span>(b.name <> i.name or b.telphone <> i.telphone) </span></code>
Copy after login
<code><span> </span></code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
<span><code>--</code><code>插入新增的数据 </code></span>
Copy after login
<span><code>insert srv2.</code><code>库名.dbo.author(id,name,telphone) </code></span>
Copy after login
<code><span>select id,name,telphone from author i </span></code>
Copy after login
<code><span>where not exists( </span></code>
Copy after login
Copy after login
<span><code>select * from srv2.</code><code>库名.dbo.author where id=i.id) </code></span>
Copy after login
<code><span> </span></code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
<span><code>--</code><code>删除已经删除的数据(如果需要的话) </code></span>
Copy after login
<code><span>delete b </span></code>
Copy after login
<span><code>from srv2.</code><code>库名.dbo.author b </code></span>
Copy after login
<code><span>where not exists( </span></code>
Copy after login
Copy after login
<code><span>select * from author where id=b.id)</span></code>
Copy after login
<span>go</span>
Copy after login

以上就介绍了经典SQL语句大全,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template