有用的SQL

 1 删除、添加、更改表结构

Alter table dictionary  Drop Column  dic_id  ;
Alter table dictionary  Add dic_id  Int IDENTITY(1,1) ;
Alter table    student  Add    isValidate  int  default(1)  not null;  --加了 default(1) 必须添加 not  null 否则默认值 不生效 
Alter table <表名> alter column <字段名> 新类型名(长度)  更改字段长度

 2 --mysql 更改某个字段为主键 自增 

ALTER TABLE t_sys_person  MODIFY id INT AUTO_INCREMENT PRIMARY KEY
 

 3 给一个字段添加唯一索引

  

   个人理解,不是主键创建非聚集索引就可以。

 

ALTER TABLE user_tab   ADD CONSTRAINT ind_username UNIQUE NONCLUSTERED(username ) ;
 

 

   

给表名 tableName 添加两个字段的联合索引 
CREATE UNIQUE NONCLUSTERED INDEX ind_索引名字  ON  tableName
(
 uid  ASC,
  name  ASC
) 

  

   

CREATE UNIQUE NONCLUSTERED INDEX ind_索引名字  ON   表名
(
 索引字段   ASC 
) 

 

4 --删除表数据,oracle可以回滚

delete from dictionary  ;

 5 清理user表的数据,数据不会回滚

 

truncate table  dbo.user

 6 sqlserver索引归零

DBCC CHECKIDENT ('dictionary', RESEED, 0 ) ; 

 7 查询数据库中所有表  以table_为前缀的(sqlserver)

  SELECT 'select * from '+TABLE_NAME 
  FROM INFORMATION_SCHEMA.tables  WHERE  TABLE_NAME LIKE 'table_%'

 8 查询重复数据 

 

select * from user_tab where username in 
(
  select username  from user_tab group by memberid having count(username )>1
)

 9 sqlserver 夸数据库完成一个表数据导入到另一个表,从main库的user表导入到temp库的user表

  

insert into main.dbo.user select * from temp.dbo.user
insert  into user_new(name ,sex )  select name,sex from user

 10 创建备份表user_bak并且将user表数据导入到user_bak中 

  

select * into user_bak FROM  user 

 11  INSTR  查找字符串在另一个字符串中什么位置,也可以用判断一个字符串在另一个字符串中是否存在

    使用情景:字符串 “黑龙江省双城市朝阳乡”,当我们想把这个字符串分割成省市乡的时候可以根据这个字符串用sql在数据库中比对找出相应的数据

 

1 mysql中 INSTR(str,substr) 
返回子串substr在字符串str中的第一个出现的位置
第二个字符串匹配第一个字符串中位置
2 oracle中 Instr(string, substring, position, occurrence)
	INSTR(源字符串, 目标字符串, 起始位置, 匹配序号)  ,第二个字符串匹配第一个字符串的位置
	string:代表源字符串; substring:代表想聪源字符串中查找的子串 ;
	position:代表查找的开始位置,该参数可选的,默认为 1; 
	occurrence:代表想从源字符中查找出第几次出现的substring,该参数也是可选的,默认为1;
3 CHARINDEX ( expression1 , expression2 [ , start_location ] )
   Expression1是要到expression2中寻找的字符中,
   start_location是CHARINDEX函数开始在expression2中找expression1的位置。

 

 12  两个表联合查询取数据  一个字段去重 另一个字段随机取 

  

select max(随机取的字段) ziduan1 ,  需要去重的字段 ziduan2 
from biao1 与biao2 的联合 
gruop by  需要去重的字段

 13 mysql时间字段设置当前值

    

5.5的版本只支持timestamp 设置now
alter table  gateway_api MODIFY COLUMN    update_date timestamp not null DEFAULT   NOW()

 

5.6应该可以用datetime类型设置默认值
alter table  gateway_api MODIFY COLUMN    update_date datetime not null DEFAULT   NOW()

   

创建的时候设置:
`update_date` timestamp  not null DEFAULT   NOW() ,

 

 

猜你喜欢

转载自username2.iteye.com/blog/1881558