阿里云折扣码

轻云博客 > SQL Server数据库设计 > SQL变量、Substring、charindex、case函数、去除重复

SQL变量、Substring、charindex、case函数、去除重复

作者:Aisencici / 日期:2014-5-9 9:05:00 / 分类:SQL Server数据库设计 / 浏览:3284

isnull(aa,0)
删除表数据:

truncate table aaa
 

添加字段:

ALTER TABLE table1 ADD col1 varchar(200) DEFAULT '2008-05-22'

修改字段名:

alter table table1 rename column col1 to col2;

修改字段属性:

alter table table1 alter column col1 varchar(200) not null;

修改默认值

alter table table1 add constraint df default('嘿嘿') for col1;
 

insert into table1(col1,col2)

  select col1,col2

  from table2 where table2.id=1


update t
   set 
t.col1 = o.col1
  from 
table1 AS t
         inner join

       
table1 AS o
         on 
t.id = o.id

//第一个参数是要截取的对象,第二个参数是截取的起始位置(从1开始),第三个参数是截取的长度

select Substring('1234567890',-1,3)


//第一个参数是要查找的字符,第二个参数是查找的对象,字符串的索引是从1开始的

select charindex('.','132.12.3')


//获取字符串的长度,参数为要查找的对象

len('123456')


//将一个字符串反转

select reverse('hello,world') 

将得到如下的输出:dlrow,olleh 


//获取最后一次”-“出现的位置

charindex('-',reverse(@str)) 

//获取最后一个”-“后面的字符 

reverse(substring(reverse(@str),1,charindex('-',reverse(@str))-1))


//类型转换

CAST(@XX AS char(20))

CONVERT(char(20), @XX)

cast(0 as bit)


--简单case函数

case sex

              when   '1'   then  '男'

              when   '2'   then  '女'

              else     '其他'   end


--case搜索函数

case      when  sex = '1'   then  '男'

              when  sex = '2'   then  '女'

              else    '其他'   end


//申明及使用变量

declare @OldItemPath nvarchar(500);

select @OldItemPath=‘123’;

总结如下:
select distinct name from table打开不重复记录的单个字段
select * from table where fid in(Select min(fid) FROM table group by name)打开不重复记录的所有字段值
select   from  table  where  name in(select  name  from  table  group  by  name    having  count(name)=1)打开不重复任意次数的所有记录

//关键字distinct,去除重复项

select distinct ip,city from table2//关键字distinct,去除重复项

本文标签:Substring
From:Aisencici
分享到: