语法

  IN和EXISTS:IN适合于外表大而内表小的情况;EXISTS适合于外表小而内表大的情况。

  示例:

  select * from t1 where t1.x in ( select t2.y from t2 )

  select * from t1 where exists ( select null from t2 where t2.y = t1.x )

  说明:

  in 事实上可以理解为:

    select * from t1, (select distinct y from t2 ) t2  
           where t1.x = t2.y;

    ——如果你有一定的SQL优化经验,从这句很自然的可以想到t2绝对不能是个大表,因为需要对t2进行全表的“唯一排序”,如果t2很大这个排序的性能是不可忍受的。但是t1可以很大,为什么呢?最通俗的理解就是因为t1.x=t2.y可以走索引。但这并不是一个很好的解释。试想,如果t1.x和t2.y都有索引,我们知道索引是种有序的结构,因此t1和t2之间最佳的方案是走merge join。另外,如果t2.y上有索引,对t2的排序性能也有很大提高。
    
   exists 可以理解为:

    for x in ( select * from t1 )
    loop
       if ( exists ( select null from t2 where y = x.x )
       then 
          OUTPUT THE RECORD!
       end if
    end loop

    ——这个更容易理解,t1永远是个表扫描!因此t1绝对不能是个大表,而t2可以很大,因为y=x.x可以走t2.y的索引。
    综合以上对IN/EXISTS的讨论,我们可以得出一个基本通用的结论:IN适合于外表大而内表小的情况;EXISTS适合于外表小而内表大的情况。



函数

  LTRIM  删除起始空格后返回字符表达式。返回类型 varchar

示例
下例使用
LTRIM 字符删除字符变量中的起始空格。

DECLARE@string_to_trimvarchar(60)
SET@string_to_trim='     Five spaces are at the beginning of this
   string.
'
SELECT'Here is the string without the leading spaces: '+
  
LTRIM(@string_to_trim)
GO

下面是结果集:

------------------------------------------------------------------------
Here is the string without the leading spaces: Five spaces are at the beginning of this string.            

(
1 row(s) affected)




RTRIM 截断所有尾随空格后返回一个字符串。返回类型 varchar

示例
下例显示如何使用
RTRIM 删除字符变量中的尾随空格。

DECLARE@string_to_trimvarchar(60)
SET@string_to_trim='Four spaces are after the period in this sentence.    '
SELECT'Here is the string without the leading spaces: '+CHAR(13) +
  
RTRIM(@string_to_trim)
GO

下面是结果集:

(
1 row(s) affected)
------------------------------------------------------------------------
Here is the string without the leading spaces: Four spaces are after the period in this sentence.          
(
1
row(s) affected)

posted on 2008-03-17 17:13  skins  阅读(296)  评论(0)    收藏  举报