Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
主要是一行的数据某些字段整成一个table,对此table进行操作即可
基础:select *, (select orderno) as new from bdorder , 可多次用select操作字段
扩展:可多次用select 取出数据,union成一个table 处理
举例:取出一行中最大的值
  
IF NOT OBJECT_ID('[tb]') IS NULL
    DROP TABLE [tb]
GO
CREATE TABLE [tb](
a SMALLINT,
b SMALLINT,
c SMALLINT,
d SMALLINT,
e SMALLINT,
f SMALLINT,
g SMALLINT 
)
INSERT [tb]
SELECT 1,2,3,4,5,2,3 UNION ALL
SELECT 4,5,6,7,7,2,0 UNION ALL
SELECT 4,9,6,7,7,9,6
GO
--SELECT * FROM [tb]
 
-->SQL查询如下:
 
SELECT *,
    (SELECT MAX(a)
     FROM(
       SELECT a UNION ALL       --用select 取出值union成table
       SELECT b UNION ALL
       SELECT c UNION ALL
       SELECT d UNION ALL
       SELECT e UNION ALL
       SELECT f UNION ALL
       SELECT g
       ) AS t   
    ) AS maxvalue
FROM tb


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

1,若或一字段值设置为n个空串即: ‘????????????????? ‘? 但在存储时依然会存为”,长度为0, 即数据库会自动完成trim操作, 故可用filed <> ” 来避免为空的字段
2,若字段值设置为’a???? ‘ ,则存储时为’a’, 长度为1
3,若字段值设置为’? a???? ‘ ,则存储时为’? a’, 长度为3
即:数据库会自动去掉字段值最后一个


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

declare @temp1 varchar(20)
select @temp1=orderdate from bdorder
where orderno = ‘J090825A001′

print @temp1

select * from bdorder
where orderdate = @temp1

执行上述语句,结果为空!即使@temp1有值
原因:时间类型的优先级高于字符型,所以当比较一个DATETIME类型的数据和一个字符串的时候,字符串首先会转化成DATETIME。
select @temp1=orderdate ,因datetime优先级比@temp1优先级高,为varchar类型@temp1赋值的时候要向下转型,
默认调用convert(varchar(20),orderdate,100) 转换成mon dd yyyy hh:miAM(或 PM)格式。
而当进行比较时where orderdate = @temp1,@temp1因向上转型,保持数据不平(参考int向上转为float),此时@temp1为’04? 6 2010? 8:36AM’,而数据库中的日期为’2010-04-06 08:36:38′, 二者相比当然是得不到结果的。

注:sql server中DateTime默认存储方式为:yyyy-mm-dd hh:mi:ss(24h),当为varchar赋值时,默认转换成了mon dd yyyy hh:miAM(或 PM)格式,二者再进行比较,就会出问题。即:默认存储方式与默认转换方式不同造成的。

解决方案:为varchar赋值时取消默认,即:
select @temp1=convert(varchar(20),orderdate,120) from bdorder where orderno = ‘J090825A001’


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

RAISERROR(‘该客户已经分配给了(%s)’, 16, 1, @description), 在程序中通过try..catch捕捉,消息就是e.Message,前提是指定严重级别为11-19,如此时的16

RAISERROR ( { msg_id | msg_str | @local_variable }
????{ ,severity ,state }
????[ ,argument [ ,...n ] ] )
????[ WITH option [ ,...n ] ]

?

msg_id
使用 sp_addmessage 存储在 sys.messages 目录视图中的用户定义错误消息号。用户定义错误消息的错误号应当大于 50000。

msg_str
用户定义消息,格式与 C 标准库中的 printf 函数类似。当指定 msg_str 时,RAISERROR 将引发一个错误号为 5000 的错误消息。因为此时用的是str,不是msg_id,sys.messages中没有存此错误信息,但这个函数功能就是抛出错误,只能由系统来提供。

severity
用户定义的与该消息关联的严重级别。当使用 msg_id 引发使用 sp_addmessage 创建的用户定义消息时,RAISERROR 上指定的严重性将覆盖 sp_addmessage 中指定的严重性。

在严重级别为 11 到 19 的情况下在 TRY 块中运行的 RAISERROR 会将控制传输至关联的 CATCH 块。指定严重级别为 10 或更低以使用 RAISERROR 返回 TRY 块中的消息,而不必调用 CATCH 块。

state
介于 1 至 127 之间的任意整数。state 的负值默认为 1。值为 0 或大于 127 会生成错误。

如果在多个位置引发相同的用户定义错误,则针对每个位置使用唯一的状态号有助于找到引发错误的代码段


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

直接在目标数据库上还原会出现:“备分集中的数据库备分与现有的数据库不同”的错误,
解决方法:解决办法:选项 -->还原选项 -->覆盖现有数据库 --> 确定


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

row_number() 的使用

WITH OrdersByOrderIDASC AS
(
SELECT
top 10 id,orderno, row_number() over(order by orderdate desc) as rowid
FROM bdorder
)

select * from OrdersByOrderIDASC
where rowid >=3 and rowid <=10 with as 用法:把重复用到的SQL语句放在with as 里面,取一个别名,后面的查询就可以用它 这样对于大批量的SQL语句起到一个优化的作用,而且清楚明了 上面等同于: select * from ( SELECT top 10 id,orderno, row_number() over(order by orderdate desc) as rowid FROM bdorder )a where rowid >=3 and rowid <=10 注:(1) with 必须直接跟使用CTE的SQL语句(如select、insert、update等),否则,CTE将失效。 (2) 可以引用自身(递归),也可以引用在同一 WITH 子句中预先定义的 CTE。不允许前向引用。 (3) . 不能在 CTE_query_definition 中使用以下子句: COMPUTE 或 COMPUTE BY ORDER BY(除非指定了 TOP 子句) INTO 带有查询提示的 OPTION 子句 FOR XML FOR BROWSE


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

保留sysindexes是为了向后兼容sql server2000之前的版本,以后可能就不再使用,而是以sys.为主
故查询一个表有多少行时可用:

SELECT *
FROM sys.partitions where object_id = object_id(‘bdorder’) and index_id = 1


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

select b.name,a.rowcnt from sysindexes a,sysobjects b
where a.id=b.id and a.indid<=2 and b.xtype='u' rowcnt bigint 基于 indid = 0 和 indid = 1 的数据级行计数。 故用a.indid <= 2 单个表记录数,占用空间数:sp_spaceused 'bdorder' 数据库所有表各个记录数,占用空间数: EXEC sp_MSforeachtable @command1="sp_spaceused '?'"


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
select name 
from sysobjects a
where exists(
        select 1 from syscolumns b
        where name = 'customerid'
        and b.id =a.id
    )


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

取出大量数据进行操作时,游标慢一些,可用临时表与表变量
临时表:
CREATE TABLE dbo.#News
  (
  News_id int NOT NULL,
  NewsTitle varchar(100),
  NewsContent varchar(2000),
  NewsDateTime datetime
  )
  INSERT INTO dbo.#News (News_id, NewsTitle, NewsContent, NewsDateTime)
  VALUES (1,’BlueGreen’, ‘Austen’, 200801, GETDATE())
  SELECT News_id, NewsTitle, NewsContent, NewsDateTime FROM dbo.#News

  DROP TABLE dbo.[#News]? –操作完之后删掉

表变量:DECLARE @News table
  (
  News_id int NOT NULL,
  NewsTitle varchar(100),
  NewsContent varchar(2000),
  NewsDateTime datetime
  )
  INSERT INTO @News (News_id, NewsTitle, NewsContent, NewsDateTime)
  VALUES (1,’BlueGreen’, ‘Austen’, 200801, GETDATE())
  SELECT News_id, NewsTitle, NewsContent, NewsDateTime FROM @News

临时表分为本地和全局两种,本地临时表的名称都是以“#”为前缀,只有在本地当前的用户连接中才是可见的,当用户从实例断开连接时被删除。全局临时表的名称都是以“##”为前缀
 表变量创建的语法类似于临时表,区别就在于创建的时候,必须要为之命名。表变量是变量的一种,表变量也分为本地及全局的两种,本地表变量的名称都是以“@”为前缀,只有在本地当前的用户连接中才可以访问。全局的表变量的名称都是以“@@”为前缀,一般都是系统的全局变量
临时表存放在磁盘上,而表变量存于内存中,就是一变量。


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

1.清空日志
DUMP TRANSACTION 库名 WITH NO_LOG

2.截断事务日志:
BACKUP LOG 数据库名 WITH NO_LOG

3.收缩数据库文件(如果不压缩,数据库的文件不会减小
企业管理器–右键你要压缩的数据库–所有任务–收缩数据库–收缩文件
–选择日志文件–在收缩方式里选择收缩至XXM,这里会给出一个允许收缩到的最小M数,直接输入这个数,确定就可以了
–选择数据文件–在收缩方式里选择收缩至XXM,这里会给出一个允许收缩到的最小M数,直接输入这个数,确定就可以了

注意:可能还有个原因是日志文件设置的大小过小,右键数据库-属性-文件-日志文件的初始大小设置大一些


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
1,同一服务器上  select * from brm_lvjian.dbo.bdorder  或 select * from brm_lvjian..bdorder
2,不同服务器上数据库的访问
(1)长久式:在本地服务器上创建远程连接
exec sp_addlinkedserver   'dpserver', ' ', 'SQLOLEDB ', '192.168.18.140'
exec sp_addlinkedsrvlogin 'dpserver ', 'false ',null, 'sa', 'sa'
select *  from dpserver.brm_lvjian_new.dbo.bdcustomerprotect    -- 执行:
exec sp_dropserver 'dpserver', 'droplogins'  --删除连接
注:1,或者在数据库 -- 服务器对象 -- 链接服务器上操作
查看链接服务器
sp_helplinkedsrvlogin
详细信息:select * from sys.servers
2,不可select * into 链接服务器...,而要用 insert into 链接服务器..       select ...
 注:在开Rpc的时候提示:不允许对系统目录进行即席更新! 可利用sql语句解决,方法:
 执行:
 EXEC master.dbo.sp_serveroption @server=N'serverstatistics', @optname=N'rpc', @optvalue=N'true'
 GO
 EXEC master.dbo.sp_serveroption @server=N'serverstatistics', @optname=N'rpc out', @optvalue=N'true'
 GO 
 (上述代码可通过右键链接服务器,编写链接服务器脚本为 - CREATE-新查询编辑器窗口得到。)
3,设置超时时间,防止链接服务器挂掉时,无限卡
dbo.sp_serveroption @server=N'serverstatistics', @optname=N'connect timeout', @optvalue=15
connect timeout:连接到链接服务器时的超时值(秒),如果为 0,则使用 sp_configure 的默认remote query timeout 选项值。
query timeout:查询超时值 链接服务器上执行的查询的超时值(秒)。如果为 0,则使用 sp_configure 的默认 query wait 选项值。

4,测试链接服务器是否链接成功。declare @srvr nvarchar(128);
declare @retval int;

SET @srvr = 'oaserver'
EXEC @retval = sys.sp_testlinkedserver @srvr
SELECT @retval

0(成功)或 1(失败)








(2)短暂式:
1)openrowset
    select * from openrowset( 'SQLOLEDB ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名)
     insert openrowset( 'SQLOLEDB ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名)
    select *from 本地表 

2)opendatasource
SELECT   * FROM   opendatasource( 'SQLOLEDB ', 'Data Source=ip/ServerName;User ID=登陆名;Password=密码 ' ).test.dbo.roy_ta 

3)openquery
select *
FROM openquery(ITSV, 'SELECT * FROM 数据库.dbo.表名 ')

3,链接服务器与事务
在事务中,访问链接服务器,要注意:
1)本地链接服务器内容不能在本地服务器事务中访问,因为链接服务器与发起事务服务器是同一台,故直接引用数据库名称即可。不需要转来转去。
2)在发起事务的服务器上访问链接服务器,在存储过程中执行语句前,要set xact_abort on,不然一般会报错如:
无法启动链接服务器 "bim" 的 OLE DB 访问接口 "SQLNCLI" 的嵌套事务。由于 XACT_ABORT 选项已设置为 OFF,因此必须使用嵌套事务。

4,执行链接服务器上的函数
DECLARE @Customerid int
SET @Customerid =  (SELECT  * from OPENQUERY(BRMSERVER,'select .dbo.[GetCustomerIdByTel](0,18620023427,0)'))
SELECT @Customerid


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

内存要比磁盘读取速度快很多。
数据在sqlserver上执行,就是在磁盘上读取,比相应的在内存中读取速度当然慢许多,不过要在内存中执行,不得不要将数据集存到内存中,造成了I/O开销,二者加起来,内存读取速度也将慢下来。内存与磁盘如何平衡?一个是高读取速度,但I/O开销大,一个是低读取速度,但I/O开销小。
故当:可取到的数据集较小时,可放到内存中,利用内存的高读取速度进行执行,以提高整体运行速度。

当在数据库上运行速度慢时,可考虑将数据集存放到内存中读取,试下速度。取速度最小的。
典型情况:对某一大表(30个字段)的某一列按多个条件进行count统计,在sql server运行时,开销很大,可考虑将这一列取出放到内存中再进行据条件的count操作。
注:big表有30个字段,1741笔资料,smail有1个字段,也是1741笔资料
select count(1) from big? select count(1) from smaill?
即使两者行数相同,执行速度也会差很多,因为big表要扫描整个表,而这个表有30个字段,每个字段都要扫描,


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

?select * from bdorder a join frmuser b on a.salesstaff = b.account and a.salesstaff like ‘asong%’
?select * from bdorder a join frmuser b on a.salesstaff = b.account and? b.account like ‘asong%’
bdorder 与 frmuser有相同的用户,在where条件中选择b.account进行筛选比用bdorder的salesstaff要好的多,因为不可避免的是bdorder有重复的salesstaff,而frmuser则不会有重复,就少了一些比较。
即:在使用join时,where条件选择数据较少的表的字段进行筛选。


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

 --检查sqlserver所在服务的运行账号是否有权限访问共享文件夹,没有的话右键添加写权限
 --检查方法:建立一网络驱动器,右键属性安全
 --注:若sqlserver在localsystem账号下面运行,是访问不了共享文件夹的,要改成有权限的账号,如network services

 --开启权限
sp_configure 'show advanced options', 1;
go
reconfigure;
go

 EXEC sp_configure 'xp_cmdshell', 1

GO

reconfigure;
go

DECLARE @DesAddress NVARCHAR(500),@DesAccount NVARCHAR(100),@DesPassword NVARCHAR(100), @DataBaseName VARCHAR(100)
SET @DesAddress = '\\172.16.88.204\soft-0509\aa'
SET @DesAccount = 'administrator'
SET @DesPassword = 'Lvshou!@#'
SET @DataBaseName = 'master'

DECLARE @bakName VARCHAR(500)
SET @bakName = @DataBaseName + '_' +  convert(varchar(10),getdate(),112) + '.bak'
SET @bakName = @DesAddress + '\' + @bakName
--print @bakName

DECLARE @sql NVARCHAR(1000)

--连接共享,打开通道
SET @sql = 'net use Y: '+ @DesAddress+ ' ' + @DesPassword + ' ' +'/user:'+@DesAccount
PRINT @sql
EXEC master..xp_cmdshell @sql

--备份
SET @sql = 'backup database ' +@DataBaseName + ' TO DISK = ' + QUOTENAME(@bakName,'''')
--PRINT @sql
EXEC (@sql)

--删除一周前备份
SET @sql = 'del ' + @DesAddress + '\' + @DataBaseName + '_' +  convert(varchar(10),dateadd(day,-7,getdate()),112) + '.bak'
--PRINT @sql
EXEC master..xp_cmdshell @sql

--执行关闭关掉通道
exec master..xp_cmdshell 'net use Y: /delete /y' 

--关闭权限
EXEC sp_configure 'xp_cmdshell', 0

GO

reconfigure;
go


 sp_configure 'show advanced options', 0
go
reconfigure;
go


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

1,nchar、nvarchar则最多存储4000个字符,不论是英文还是汉字;
而char、varchar最多能存储8000个英文,4000个汉字。
2,NCHAR、 NVARCHAR、NTEXT。这三种从名字上看比前面三种多了个“N”。它表示存储的是Unicode数据类型的字符。我们知道字符中,英文字符只需要一个字节存储就足够了,但汉字众多,需要两个字节存储,英文与汉字同时存在时容易造成混乱,Unicode字符集就是为了解决字符集这种不兼容的问题而产生的,它所有的字符都用两个字节表示,即英文字符也是用两个字节表示。nchar、nvarchar的长度是在1到4000之间。和char、 varchar比较起来,
即:varchar一个字节存一个字母,而nvarchar需要有两个,故在8000个存储空间下,nvarchar最大可以存4000个。


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

sp_lock
dbcc inputbuffer(53)
kill 53
SQL SERVER Profiler

Microsoft SQL Server 2005 提供了一些工具来监控数据库。方法之一是动态管理视图。动态管理视图 (DMV) 和动态管理函数 (DMF) 返回的服务器状态信息可用于监控服务器实例的运行状况、诊断问题和优化性能。

常规服务器动态管理对象包括:

dm_db_*:数据库和数据库对象

dm_exec_*:执行用户代码和关联的连接

dm_os_*:内存、锁定和时间安排

dm_tran_*:事务和隔离

dm_io_*:网络和磁盘的输入/输出

此部分介绍为监控 SQL Server 运行状况而针对这些动态管理视图和函数运行的一些常用查询。


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
declare @salesstaff varchar(50)
set @salesstaff = null
SELECT @SalesStaff = SalesStaff FROM bdCustomerAllocate WHERE Departmentid = 4 AND CustomerID = -111
if ( @salesstaff  is   null )
begin
    print 'null'
end
else
begin
    print 'sdf'
end

若数据库中没有此记录,则不会给 @SalesStaff赋值,它会保留原值,故最好在赋值前将其设为NULL


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

(1)select * from bdorder
(2) select * from bdorder
order by orderdate desc
前者执行为15% 而后者要85% 差了5倍多!
故在用DESC 要慎用,效率太低!

典型应用:
左连接取出连接表符合条件的第一条记录
left? join bdship d(NOLOCK)
on d.orderno = c.orderno
AND d.id=(select top 1 id from bdship m where m.orderno = d.orderno order by id desc )
应改为:
left? join bdship d(NOLOCK)
on d.orderno = c.orderno
AND d.shipdate=(select max(shipdate) from bdship m where m.orderno = d.orderno? )


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
 CREATE                PROCEDURE [dbo].[bdCustomerAllocate_sel]
@TranType varchar(40) = NULL,
@Id int = NULL,
@CustomerID int = NULL,
@OpenDate varchar(20) = NULL,       //在 AS 之前的是形参,则程序中传值,程序中传值个数可少于形参个数,前提是没有被传的形参要赋值,如NULL

AS
DECLARE @CustoemrName varchar(20)        //在As之后用 Declare定义变量,只在存储过程内部使用,不是形参。
SET @CustomerName = ''
IF(@TranType = 'personalcustomerlist')
BEGIN
    SELECT a.id, b.CustomerName, b.Address, b.Tel, 
    (SELECT TOP 1 FollowDate FROM bdFollowRecord T(nolock)
        WHERE T.AllocateID = a.ID) AS FollowDate
    FROM  bdCustomerAllocate a(NOLOCK)
    JOIN bmdCustomer b(NOLOCK)
    ON a.CustomerID = b.ID    
    WHERE a.IsValid = 1
END