现在的位置: 首页 > 综合 > 正文

sql语句集锦

2013年08月07日 ⁄ 综合 ⁄ 共 5718字 ⁄ 字号 评论关闭
一、主要是需要更新mssqlServer 的时候需要进行一些是否存在的判断,在mssql2000 和 2005 上测试没有问题

 

 

 

 

今天给新同事讲数据维护过程的时候,他提出了写一个存储过程来检查日志表出错之后调用相关的存储过程,我们的日志表当中写入的表名和相应存储过程名称的差别是多了一个etl_,因此ETL_||table就是存储过程的名称.但是在编译过程当中无法将变量的存储过程名称在嵌套时执行,经过多方查找,一度怀疑是否可以执行这种变量式的存储过程,但是终于找到了方法,存储过程如下:

create or replace procedure yx_etl_proc as
 cursor tb is select  'ETL_'||table_name
             from etl_log
             where end_time is null and (table_name,start_time) in  (select table_name,max(start_time)
             from etl_log where start_time>trunc(sysdate)
             group by table_name);
       c_proc_name etl_log.table_name%type;
begin
 
open tb;
loop
fetch tb into c_proc_name;
exit when tb%notfound;
execute  immediate 'begin '||c_proc_name||';end;';  
commit;
end loop;
close tb;
end yx_etl_proc;

粗体部分就是嵌套存储过程的执行方法。

 

 

二、 insert into select

 

三、排重

 

四、如何合并多条记录成为一条记录

【参考http://zhidao.baidu.com/question/178504075.html?push=ql】

 

 

五 重命名字段

IF COL_LENGTH('USP_UserGroup','UserGroupSecurity') IS NOT NULL
	EXEC sp_rename 'USP_UserGroup.UserGroupSecurity','UserGroupLevel','COLUMN'
ELSE IF COL_LENGTH('USP_UserGroup','UserGroupLevel') IS NULL
	ALTER TABLE dbo.USP_UserGroup ADD UserGroupLevel int NOT NULL DEFAULT 0

六、如果杀死正在执行的存储过程。

我后来用sp_who查看,然后通过kill命令直接杀死的。多亏兄弟告诉我用KILL。 
sp_who --列出id列表,需要查询某个用户可以 sp_who "username"
kill 67 --杀掉该id
查询进程连接:

select * from sysprocesses where dbid in (select dbid from sysdatabases where name='MyDatabase') 

七、判断自定义方法是否存在,如果不存在,则创建

if exists(select 1 from sysobjects where id=object_id('fn_GetCategoryCodebycode') 
and objectproperty(id,'IsInlineFunction')=0)
drop function [fn_GetCategoryCodebycode] 

go
create function [dbo].[fn_GetCategoryCodebycode](@CateCode nvarchar(64)) 
returns int
as
begin
declare @ret int
SELECT TOP 1 @ret=CategoryID 
FROM CMF_CategoryDetail a  where CategoryTypeID=1  
and ( charindex(CategoryCode,@CateCode) = 1) ORDER BY Len(CategoryCode) DESC
return @ret
end
go

【上篇】
【下篇】

抱歉!评论已关闭.