SQL笔记

1. 获得本月第一天和最后一天,将GETDATE()换成指定日期可以得到指定日期所在月份的第一天和最后一天。

SELECT     DATEADD(ms,-3,DATEADD(mm,DATEDIFF(m,0,GETDATE())+1,0)) 
SELECT     DATEADD(ms,1,DATEADD(mm,DATEDIFF(m,0,GETDATE()),0)) 

2. 字符相关函数

str() 由数字数据转换来的字符数据。
语法

STR ( float_expression [ , length [ , decimal ] ] ) 


参数
float_expression
是带小数点的近似数字 (float) 数据类型的表达式。不要在 STR 函数中将函数或子查询用作 float_expression。
length
是总长度,包括小数点、符号、数字或空格。默认值为 10。
decimal   
是小数点右边的位数。

CHARINDEX()返回字符串中指定表达式的起始位置。

CAST 和 CONVERT
  将某种数据类型的表达式显式转换为另一种数据类型。 CAST 和 CONVERT 提供相似的功能。

decimal 和 numeric
带精度和小数位数的数据类型

decimal(p[,s])  numeric(p[,s])   

p:精度  s:小数点后面的位数

3. 无线级树(转)

--处理示例

--示例数据
create table tb(ID int,Name varchar(10),ParentID int)
insert tb select 1,'AAAA'    ,0
union all select 2,'BBBB'    ,0
union all select 3,'CCCC'    ,0
union all select 4,'AAAA-1'  ,1
union all select 5,'AAAA-2'  ,1
union all select 6,'BBBB-1'  ,2
union all select 7,'CCCC-1'  ,3
union all select 8,'CCCC-2'  ,3
union all select 9,'AAAA-1-1',4
go

--创建处理的函数
create function f_id()
returns @re table(id int,level int,sid varchar(8000))
as
begin
    
declare @l int
    
set @l=0
    
insert @re select id,@l,right(10000+id,4)
    
from tb where ParentID=0
    
while @@rowcount>0
    
begin
        
set @l=@l+1
        
insert @re select a.id,@l,b.sid+','+right(10000+a.id,4)
        
from tb a,@re b
        
where a.ParentID=b.id and b.level=@l-1
    
end
    
return
end
go

--调用函数实现查询
select a.*,带缩进的Name=space(b.level*4)+a.Name
from tb a,f_id() b
where a.id=b.id
order by b.sid
go

--删除测试
drop table tb
drop function f_
原文地址:https://www.cnblogs.com/lindj0307/p/1350486.html