Home >Backend Development >PHP Tutorial >Complete collection of classic SQL statements, complete collection of sql statements_PHP tutorial

Complete collection of classic SQL statements, complete collection of sql statements_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:05:31987browse

A collection of classic SQL statements, a collection of sql statements

1. Basics

1, Description: Create database
CREATE DATABASE database-name
2, Description: Delete database
drop database dbname

3, Description: Backupsql server
--- Create backup data device
USE master
EXEC sp_addumpdevice 'disk', 'testBack', 'c:mssql7backupMyNwind_1.dat'
--- Start backup

BACKUP DATABASE pubs TO testBack

4, Description: 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 old table to create 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: The column cannot be deleted after it is added. 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. Description: 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 Must be deleted and rebuilt.
9, Description: Create 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
find: select * from table1 where field1 like '%value1%' -- The syntax of -like is very subtle, 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
maximum:
select max(field1) as maxvalue from table1
minimum
select min(field1) as minvalue from table1
11, Description: Several advanced query operators
A: UNION operator
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 any duplicate rows. When ALL is used with EXCEPT (EXCEPT ALL), duplicate rows are not eliminated.

C: INTERSECT Operator INTERSECT
operator only includes TABLE1 and TABLE2 Derive a result table by removing all rows in the table and eliminating all 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): The result set includes both matching join rows of the join table and all rows of the right join table.
C: full/cross (outer) join:
Full outer join: not only includes symbols The matching rows of the joined tables also include all records in both joined tables.
12, grouping:Group by:
One Once the grouping is completed in a table, only group-related information can be obtained after querying.
Group related information: (statistical information) count,sum,max,min,avg Grouping criteria)
When grouping in SQL Server: text, ntext, image types cannot be used Fields are used as grouping basis
The fields in the selecte statistical function cannot be put together with ordinary fields;

13, operate the database:
Separate database
: sp_detach_db; Attach database : sp_attach_db followed by indicates that attachment requires a complete path name
14. How to modify the name of the database:
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 1a8093152e673feb7aba1828c435320941 (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 of 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 value1 and value2

9, Description: How to use in
select * from table1 where a [not] in ('value1','value 2','value 4','value 6')

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, Description: 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 name order by Sort field desc) a,Table name b where b.Primary key field = a.Primary key field order by a. Sorting 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 results if the fields of top are logical indexes (the data in the logical index may be inconsistent with the data Inconsistency in the table, and if the query is in the index, the index will be queried first )

14, description: first 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 in the forum every month Ranking list, monthly hot-selling product analysis, ranking by subject scores, 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, Description: Randomly take out 10 pieces of data
select top 10 * from tablename order by newid()

18, Description: Randomly select records
select newid()

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 Involves the movement of a large amount of data. This approach is not suitable for large-volume but data operations
3), for example: when importing data into an external table, for some reason only a part of it is imported the first time. , but it is difficult to determine the specific location, so you can only import them all next time, which will produce a lot of duplicate fields. How to delete duplicate fields

alter table tablename
--
Add an auto-increment column
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
select name from sysobjects where type='U' / /U stands for 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
Computer A 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 selecting all "where 1=2" and deselecting all "where 1=2",
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 安定 '+ @strWhere 2, Shrink database
--Rebuild 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 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 0c39aa2c357d9d33435af446b56cebc160

  break

 else

    continue

end

 

数据开发-经典


1.按姓氏笔画排序:
Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as //从少到多

2.数据库加密:
select encrypt('原始密码')
select pwdencrypt('原始密码
')
select pwdcompare('原始密码','加密后密码') = 1--相同;否则不相同 encrypt('原始密码
')
select pwdencrypt('原始密码
')
select pwdcompare('原始密码','加密后密码') = 1--相同;否则不相同

3.取回表中字段:
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='
A'
set @sql='select '+right(@list,len(@list)-1)+' from 表A
exec (@sql)

4.查看硬盘分区:
EXEC master..xp_fixeddrives

5.比较A,B表是否相等:
if (select checksum_agg(binary_checksum(*)) from A)
     =
    (select checksum_agg(binary_checksum(*)) from B)
print '
相等'
else
print '不相等'

6.杀掉所有的事件探察器进程:
DECLARE hcforeach CURSOR GLOBAL FOR SELECT 'kill '+RTRIM(spid) FROM master.dbo.sysprocesses
WHERE program_name IN('SQL profiler',N'SQL 
事件探查器')
EXEC sp_msforeach_worker '?
'

7.Record search:
beginning to NRecords
Select Top N * From Table
----------------------------------
N
toM records(must have a primary index
ID)
Select Top M-N * From
Table Where ID in (Select Top M ID From Table) Order by ID Desc
-- --------------------------------
N
To the end Record
Select Top N * From Table Order 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 the 31 to The 40th record.

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, so As a result, the data that 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 is not auto-increasing, problems will occur

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

Example2: Query the last record in the table and don’t know how much data there is in the table,And the table structure.
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 a8093152e673feb7aba1828c43532094 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 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 the linked server when it is no longer used in the future

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 the local table into the 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 the local table into the 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 the local table into the remote table

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

select * from local table

SQL ServerBasic Functions

SQL Server Basic Functions

1. String functions Used for length and analysis

1,datalength(Char_expr) Returns the string containing the number of characters, but does not include the following spaces
2,substring( expression,start,length) takes the substring. The subscript of the string is from "1", start is the starting position, and length is the length of the string. In practical applications, len(expression) is used to obtain the length
3,right(char_expr,int_expr) returns the int_expr character on the right side of the string, and uses left to do the opposite
4,isnull( check_expression , replacement_value )If check_expression is empty, the value of replacement_value is returned. If it is not empty, the check_expression character operation class is returned

5,Sp_addtype Custom data type
For example: EXEC sp_addtype birthday, datetime, 'NULL'

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/963546.htmlTechArticle经典SQL语句大全,sql语句大全 一、基础 1 、说明:创建数据库 CREATE DATABASE database-name 2 、说明:删除数据库 drop database dbname 3 、说明:备份...
Statement:
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