SQL SERVER中一些特别地方的特别解法
--1.关于where筛选器中出现指定星期几的求解
SQL code
--环境
create table test_1
(
id int,
value varchar(10),
t_time datetime
)
insert test_1
select 1,'a','2009-04-19' union
select 2,'b','2009-04-20' union
select 3,'c','2009-04-21' union
select 4,'d','2009-04-22' union
select 5,'e','2009-04-23' union
select 6,'f','2009-04-24' union
select 7,'g','2009-04-25'
go
我们一般通过 datepart(weekday )进行求解,比如求解星期2的记录
select * from test_1
where DATEPART(WEEKDAY,t_time+@@DATEFIRST-1)=2
/*
id value t_time
----------- ---------- -----------------------
3 c 2009-04-21 00:00:00.000
*/
这里涉及到 @@datefirst 这个系统变量,一般我们用来调节不同地方的日期习惯。
如果你觉得关于这个变量很难也懒得去依赖它调节,这里还有一种方法
你可以使用一个参照日期,通过相同星期数成7的倍数的原理进行查询
select * from test_1
where DATEDIFF(DAY,'1900-01-02',t_time)%7=0
/*
id value t_time
----------- ---------- -----------------------
3 c 2009-04-21 00:00:00.000
*/
--2.关于在where筛选器中指定大小写查找的索引引用问题
SQL code
--环境
--drop table test_2
create table test_2
(
id int identity(1,1),
value varchar(10)
)
insert test_2 select
'abc' union all select
'Abc' union all select
'ABC' union all select
'aBc'
go
create clustered index in_value on test_2(value)
--我先要查找 值为'ABC'的记录 要区分大小写的
select * from test_2
where value COLLATE CHINESE_PRC_CS_AS ='ABC'
按CTRL+L看执行计划 发现时聚集索引扫描 这就说明它不是SARG,不考虑使用索引
解决方法:
select * from test_2
where value COLLATE CHINESE_PRC_CS_AS ='ABC'
and value='ABC'
go
--3.自动全局临时表
SQL code 在某些情况下,你可能需要跨会话的维护一些共享值,这里可以通过一些手段自动建立这样一个全局临时表够你使用
具体方法就是在master数据库中建立一个以sp_开头的特殊存储过程,并且使用'startup'标志此存储过程,这样每次重启数据库后都会自动运行此存储过程,
通过在存储过程中建立全局临时表,就达到
相关文档:
簡體數據庫轉繁體數據庫的問題 拜托了
ALTER DATABASE DatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE
ALTER DATABASE DatabaseName COLLATE Chinese_Taiwan_Stroke_CI_AS
ALTER DATABASE DatabaseName SET MULTI_USER WITH ROLLBACK ......
1) 选择最有效率的表名顺序(只在基于规则的优化器中有效):
ORACLE的解析器按照从右到左的顺序处理from子句中的表名,from子句中写在最后的表(基础表 driving table)将被最先处理,在from子句中包含多个表的情况下,你必须选择记录条数最少的表作为基础表。如果有3个以上的表连接查询, 那就需要选择交叉表(intersection ......
drop table father;
create table father(
id int identity(1,1) primary key,
name varchar(20) not null,
age int not null
)
drop table mother;
create table mother(
id int identity(1,1),
name varchar(20) not null,
age int not null,
husban ......
可以定义一个无论何时用INSERT语句向表中插入数据时都会执行的触发器。
当触发INSERT触发器时,新的数据行就会被插入到触发器表和inserted表中。inserted表是一个逻辑表,它包含了已经插入的数据行的一个副本。inserted表包含了INSERT语句中已记录的插入动作。inserted表还允许引用由初始化INSERT语句而产生的日志数据 ......
一个简单的例子:
先建一个C#类:
引用System.Data.Linq.dll程序集,
using System.Data.Linq.Mapping和
using System.Data.Linq 两个空间。
[Table]
public class Inventory
{
[Column]
public string Make;
[Column]
public string Color;
&nbs ......