1.如何删除表中的重复记录?
select distinct * into #temp from tab
delete tab
insert tab select * from #temp
drop table #temp
2.怎样返回数据库中用户表的表单名
select name from sysobjects where xtype='U'
select name from sysobjects where xtype = 'u' and status >=0
3.
http://community.csdn.net/Expert/topic/4191/4191899.xml?temp=.5814325
各位大大请帮个忙,
一个表中A字段是int型的自动编号,B字段是首先要获取A字段已有的自动编号数据再经过加入时间等后生成的数据,表如下
C,D(日期),E为其他数据
列名 A(自动递加) B(A字段数据+日期等) C D E
---------------------------------------------------
1 A+D . . .
2 A+D . . .
---- 建立测试环境:
create table table1(a int identity,b varchar(20),c datetime,d datetime,e int)
create proc proc1
@c datetime,
@d datetime,
@e int
as
declare @f int
insert table1 (c,d,e) values(@c,@d,@e)
select @f=@@identity
if @@error=0
begin
导出企业根据大类别。四个表就晕了。。。。。。。
--插入到临时表里
select distinct (a.id),a.corpname,a.corplinkman,a.phonenumber,a.createtime,a.address
,(select distinct d.name
from
dz_subinfoDefine as c,
dz_mainInfoDefine as d
where c.maintype = d.maintype
and c.subtype = b.infotype) as type
into #table2
from dz_corporation as a
left join dz_information as b on a.id = b.corpid
--插入到表里.需要两次是因为无法对类别(大类)进行排序
select case when type IS NULL then '未知类别' else type end as 大类别,corpname as 名称 ,corplinkman as 联系人,phonenumber as 联系电话,address as 地址 ,createTime as 创建时间 into Table1 from #table2
order by type
----删除临时表
drop table #table2
好的方法????找不到........可能是数据库设计的不好.
通过另一个表来更新本表的记录.
begin transaction
update EPM_Employeelist set loginname =b.loginname,password= b.password
from zfj_users as b
where
EPM_Employeelist.userid = b.userid
and corpid = 10001
rollback transaction
在in子句中如何写变量的表达式问题
declare @ids varchar(8000)
set @ids = '14501,14502,14503'
select * from table1 where charindex(','+cast(id as varchar(20))+',',','+@ids+',')>0
一个存储过程
-- 调度设置的时候更新人员状态
--EPM_EmployeeList 里的active = 1
--trace_Timer 里的active = 1
--trace_users 里的traceduration 清0
--执行例子:exec up_SetSchedule 1001,'1009,1019'
alter proc up_SetSchedule
--create proc up_SetSchedule
@nCorpId int,
@vchEmployeeIds varchar(8000),
@TimeStart DateTime,
@TimeEnd DateTime
as
declare @sql varchar(8000),@TraceSolt int
SET XACT_ABORT ON --任何一部有问题是都会回滚事务
BEGIN TRANSACTION --开始事务
--更新企业表中的起始时间
update EPM_EnterpriseList set ScheduleStart = @TimeStart,ScheduleEnd = @TimeEnd
--更新员工调度状态(清0)
update EPM_EmployeeList set activeStatus = 0 where corpid = @nCorpId and activeStatus != 0 or activeStatus is null
--Trace_Timer里员工状态清0
update Trace_Timer set activeStatus = 0 where corpid = @nCorpId and activeStatus != 0 or activeStatus is null
--Trace_Users里员工状态清0
update Trace_Users set traceDuration = 0 where traceUser in (select mobileid from EPM_EmployeeList where corpid = @nCorpId)
if (@vchEmployeeIds !='')
begin
set @sql ='update EPM_EmployeeList set activeStatus = 1 where corpid= '+convert(varchar(10),@nCorpId)+ ' and id in ('+@vchEmployeeIds+')'
exec (@sql)
--更新Trace_timer 执法局不需要对次表操作.
--set @sql ='update trace_Timer set activeStatus = 1 where corpid= '+convert(varchar(10),@nCorpId)+ ' and mobileid in ('
--set @sql= @sql+'select mobileid from EPM_EmployeeList where id in ('+@vchEmployeeIds+'))'
--exec (@sql)
select @TraceSolt = (select tracesolt from EPM_EnterpriseList where id = @nCorpId)
--更新Trace_users 有与没有corpid所以只能根据手机号了.
--set @sql ='update trace_users set traceDuration =0 where traceuser in ('
--set @sql= @sql+'select mobileid from EPM_EmployeeList where id in ('+@vchEmployeeIds+'))'
--先判断用户是否在Trace_Users里存在,如果存在则修改它,如果不存在需要添加一条记录.
--可以先增减没有的记录,然后统一更新这些记录.
--增加
exec up_SetSchedule_AddUsers @vchEmployeeIds --存储过程里执行存储过程.
--更新
set @sql ='update trace_users set createTime ='''+cast(@timeStart as varchar)+''''
set @sql= @sql+',traceTime='''+cast(DateAdd(minute,-@TraceSolt,@timeStart) as varchar )
set @sql= @sql+''',traceDuration ='''+convert(varchar,datediff(minute,@timeStart,@timeEnd))+''' where traceuser in ('
set @sql= @sql+'select mobileid from EPM_EmployeeList where id in ('+@vchEmployeeIds+'))'
exec (@sql)
end
COMMIT TRANSACTION --提交事务
GO
--增加表里不存在的记录.传递的参数为员工ID的集合(号码间用逗号分开),判断是否存在的方法,与上个相比效率高
create procedure up_SetSchedule_AddUsers
@vchEmployees varchar(8000) = ''
as
--Declare @vchEmployees varchar(8000)
--set @vchEmployees = '1172,1229,1271'
--Set @vchEmployees = ''''+replace(@vchEmployees,',',''',''')+''''
--select @vchEmployees
declare @vchMobiles varchar(8000) --手机号码集合
--set @vchEmployees = '1172,1229,1271'
SET XACT_ABORT ON --一步出现问题则全部回滚
Begin Transaction
--获得手机号码集合
set @vchMobiles = ''
select @vchMobiles = @vchMobiles+','+cast(mobileid as varchar(20)) from EPM_EmployeeList where charindex(','+cast(id as varchar(20))+',',','+@vchEmployees+',')>0
set @vchMobiles=stuff(@vchMobiles,1,1,'')
--select @vchMobiles
while charindex(',',@vchMobiles)>0
begin
insert into Trace_Users(TraceKey,MuteSMS,CreateTime,TraceUser,TraceTime,TraceSlot,TraceDuration)
select 'TRACE_TIMER',0,getdate(),left(@vchMobiles,charindex(',',@vchMobiles)-1),getDate(),30,0
where not exists(select traceUser from Trace_Users where traceUser=left(@vchMobiles,charindex(',',@vchMobiles)-1))
set @vchMobiles = stuff(@vchMobiles,1,charindex(',',@vchMobiles),'')
end
insert into Trace_Users(TraceKey,MuteSMS,CreateTime,TraceUser,TraceTime,TraceSlot,TraceDuration)
select 'TRACE_TIMER',0,getdate(),@vchMobiles,getDate(),30,0
where not exists(select 1 from Trace_Users where TraceUser=@vchMobiles)
---判断是否已经有此记录.
--rollback Transaction
Commit Transaction
go
up_SetSchedule_AddUsers '1172,1229,1271'
exec up_SetSchedule @nCorpId = N'10001', @vchEmployeeIds = N'1271,1484', @TimeStart = N'2005-11-25 8:30:00', @TimeEnd = N'2005-11-25 17:30:00'
---取消一人或多人的调度,多人之间用逗号分开
create procedure up_Schedule_Cancel
@vchEmployees varchar(8000)
as
declare @vchMobiles varchar(8000)
--declare @vchEmployees varchar(8000)
--set @vchEmployees = '1484'
--获得手机号码集合
set @vchMobiles = ''
select @vchMobiles = @vchMobiles+','+cast(mobileid as varchar(20)) from EPM_EmployeeList where charindex(','+cast(id as varchar(20))+',',','+@vchEmployees+',')>0
set @vchMobiles=stuff(@vchMobiles,1,1,'')
set xact_abort on
begin transaction
update EPM_EmployeeList set activestatus = 0
where charindex(','+cast(mobileid as varchar(20))+',',','+@vchMobiles+',')>0
update Trace_Users set traceduration = 0
where charindex(','+cast(traceUser as varchar(20))+',',','+@vchMobiles+',')>0
commit transaction
go
--获得系统对象:
sysobjects
在数据库内创建的每个对象(约束、默认值、日志、规则、存储过程等)在表中占一行。只有在 tempdb 内,每个临时对象才在该表中占一行。
--所有procedure && 名称='up_DeleteEnterprise'
select * from sysobjects where xtype = 'P' and name = 'up_DeleteEnterprise'
--所有Triger
select * from Sysobjects where xtype = 'TR'
--所有用户Table
select * from Sysobjects where xtype = 'u'
xtype的值:
C = CHECK 约束
D = 默认值或 DEFAULT 约束
F = FOREIGN KEY 约束
L = 日志
FN = 标量函数
IF = 内嵌表函数
P = 存储过程
PK = PRIMARY KEY 约束(类型是 K)
RF = 复制筛选存储过程
S = 系统表
TF = 表函数
TR = 触发器
U = 用户表
UQ = UNIQUE 约束(类型是 K)
V = 视图
X = 扩展存储过程
---判断临时表是否存在
if exists(select 1 from tempdb..sysobjects where id=object_id('tempdb..#表名') and xtype='U')
drop table #表名
--字段值为NULL转化为0,多看系统方法
isnull(字段,0)
--table1和talbe2交叉联接的结果集再和table3左联接
select a.*,c.others from
(select a.id,a.name,b.remark
from table1 a,table2 b) a
left join table3 c on a.id = c.parentid
自定义方法的使用.
--根据手机型号获得其所属模式.若模式为空或NULL则返回2(中模式)
--例子:select mms.dbo.uf_GetMobileModel(205) as aaa
alter FUNCTION uf_GetMobileModel
(@nModelId int)
RETURNS int
AS
BEGIN
--declare @nModelId int
--set @nModelId = 205
declare @Mode int
select @Mode= model from MMS_MobileChild where id = @nModelId
if @Mode = '' or @Mode is null
set @Mode = 2
--select @Mode
return (@Mode)
END
随机数自定义方法
--通过View来获得随即数字.在方法里直接使用rand()不可以的.
create view uv_GetRandom
as
select rand() as RandomValue
go
--生成n位随机数的方法
--select locationServiceNew.dbo.getRandom(10)
--比较郁闷..好麻烦
alter function GetRandom(@nLength int=4)
returns int
as
begin
declare @nStart int,@vchLength varchar(50)
set @nstart = 1
set @vchLength = '1'
if @nLength >9 set @nLength = 9 --如果随机数位数大于9那么将其修改为9
if @nLength <1 set @nLength = 1 --如果随机数位数小于1那么将其修改为1
while @nStart <= @nLength
begin
set @vchLength = @vchLength+'0'
set @nStart = @nStart+1
end
declare @floatNum float,@intNum int
--set @num=cast(left(rand(),8) as float)*1000000
select @floatNum = RandomValue from uv_GetRandom
set @intNum = cast(@floatNum*cast(@vchLength as int) as int)
return (@intNum)
end
go
--测试
select locationServiceNew.dbo.getRandom(7)
用户定义函数中不允许使用会对每个调用返回不同数据的内置函数
其中就有getdate哦
用户定义函数中不允许使用以下内置函数:
@@CONNECTIONS
@@PACK_SENT
GETDATE
@@CPU_BUSY
@@PACKET_ERRORS
GetUTCDate
@@IDLE
@@TIMETICKS
NEWID
@@IO_BUSY
@@TOTAL_ERRORS
RAND
@@MAX_CONNECTIONS
@@TOTAL_READ
TEXTPTR
@@PACK_RECEIVED
@@TOTAL_WRITE
--创建指定位的随即数
create proc up_GetRandom
@nLength int = 4, --随即数的位数.
@vchValue int output
as
declare @nStart int,@vchLength varchar(50)
set @nstart = 1
set @vchLength = '1'
if @nLength >9 set @nLength = 9 --如果随机数位数大于9那么将其修改为9
if @nLength <1 set @nLength = 1 --如果随机数位数小于1那么将其修改为1
while @nStart <= @nLength
begin
set @vchLength = @vchLength+'0'
set @nStart = @nStart+1
end
set @vchValue= cast(rand()*cast(@vchLength as int) as int)
go
--测试
declare @randomValue int
Exec up_getRandom 8,@randomValue output
select @randomValue
按照月统计
select datepart(month,createtime) as '月分',count(mobileid) as '数量'
from User_answer
where createtime >= '2005-4-29' and accessnumber = 1111111
group by datepart(month,createtime)
-------------------------------------------------------------
其它
select a.fee_user as '号码',b.message as '内容',a.sendTime as '时间'
into test
from his_smdr a
left join his_deliver b on a.fee_User = b.src_userid
where
a.src_addr = '05555001' and a.sendtime >='2005-4-29'
and a.src_addr=b.dst_userid --需要
and datediff(ss,b.createtime,a.sendtime)<=10 and datediff(ss,b.createtime,a.sendtime)>='0'
order by sendTime desc
update table1 set b=convert(varchar,a)+convert(varchar(12),d,120) where a=@f
end
---执行存储过程
exec proc1 '2001-10-01','2001-10-20',45
select * from table1
4.事务问题
http://community.csdn.net/Expert/topic/4245/4245634.xml?temp=.663891
(1)try:
-------------------------------------------------------------------------
CREATE PROCEDURE sp_Order_UpdateOrderFormHeadByAffirm
@OrderFormHeadID int,
@AffirmPerson nvarchar(50)
AS
BEGIN TRANSACTION
DECLARE @OrderFormNo nvarchar(50), @FranchiserNo nvarchar(10), @TotalSum decimal(18,4)
--更新状态为确认
UPDATE
AD_U_HEAD_A_SSGL
SET
Tag = 1
WHERE
OrderFormHeadID = @OrderFormHeadID
IF (@@error <> 0)
BEGIN
ROLLBACK TRANSACTION
RETURN
END
------------------------------------------------------------------------------------------
--返回 订单管理(HEAD)的一些信息
SELECT
@OrderFormNo = OrderFormNo,
@FranchiserNo = FranchiserNo,
@TotalSum = TotalSum
FROM
AD_U_HEAD_A_SSGL
WHERE
OrderFormHeadID = @OrderFormHeadID
IF (@@error <> 0)
BEGIN
ROLLBACK TRANSACTION
RETURN
END
------------------------------------------------------------------------------------------
--更新 订单管理(DATA)
UPDATE
AD_U_DATA_A_SSGL
SET
Tag = 1,
AffirmPerson = @AffirmPerson,
AffirmDate = GETDATE()
WHERE
OrderFormNo = @OrderFormNo
IF (@@error <> 0)
BEGIN
ROLLBACK TRANSACTION
RETURN
END
------------------------------------------------------------------------------------------
--经销代理资信余额(MAIN)
EXEC sp_Order_UpdateCreditBalance @FranchiserNo, 0, 0, 0, @TotalSum, 0
IF (@@error <> 0)
BEGIN
ROLLBACK TRANSACTION
RETURN
END
------------------------------------------------------------------------------------------
--新增 订单确认日志(SLOG)
INSERT INTO
AD_U_SLOG_A_DDQR(OrderFormNo, GoodsNo, Quantity,
UnitPrice, ProductPackingNo,TotalQuantity, TotalSum, Rebate, FactSum)
SELECT
OrderFormNo, GoodsNo, Quantity, UnitPrice, ProductPackingNo,
TotalQuantity, TotalSum, Rebate, FactSum
FROM
AD_U_DATA_A_SSGL
WHERE
OrderFormNo = @OrderFormNo
IF (@@error <> 0)
BEGIN
ROLLBACK TRANSACTION
RETURN
END
COMMIT TRANSACTION
GO
(2)----------------------------------
CREATE PROCEDURE sp_Order_UpdateOrderFormHeadByAffirm
@OrderFormHeadID int,
@AffirmPerson nvarchar(50)
AS
SET XACT_ABORT ON
BEGIN TRANSACTION
......
(3)你说得没错 其实你那样用事务的画没什么作用,每个存储过程都是一个事务。如果用事务最好有出错的处理是否回滚之类的东西。但是要考虑好表之间的关联性,如果都是一些单独的表,可以分几个事务处理,如果是父子表还是要放在一个事务里面。保证其数据的准确
性。
4请给条如何找出重复记录的SQL语句
表 A ,有2个字段 Id--Int,Name--Varchar(20)
假设 表 A 里存储了30万记录,其中有1条记录的 ID 是重复的,现在我想找出该条记录ID,SQL语句?
select ID from A group by ID having count(1)>1
有一个触发器,触发该触发器的方法有insert,update,delete
但是,我如何可以判断我到底是用哪种方法触发该触发器
http://community.csdn.net/Expert/topic/4234/4234894.xml?temp=.3572657
create trigger 触发名 on 表名
instead of insert,update,delete
as
--insert插入
if not exists(select 1 from deleted)
begin
打印插入
end
--update更新
if exists(select 1 from inserted) and exists(select 1 from deleted)
begin
打印修改
end
--delete删除
if not exists(select 1 from inserted)
begin
打印删除
end
go
有两个表 table1 和talbe2,字段和内容如下
字段 id name id so
00 n1 00 s1
01 n2 03 s3
03 n3
怎样写一个sql语句,得到记录集
字段 id name so
00 n1 s1
01 n2
03 n3 s3
select A.*
,isnull(B.so,'') as 'so'
from table1 A
left join table2 B on A.id=B.id
获得所有触发器及其表名
select object_name(id) as 触发器名称, object_name(parent_obj) as 表名称 from sysobjects
where xtype=N'TR'
-- 由一个表向另一表插入数据.
insert into EPM_DepartmentList(id,name,parentdeptid,state,type,showindex,url,corpid)
select id,name,parentDeptid,status as state,type,showindex,url,corpid = 1001
from zfj_dept
日期:
select convert(varchar(16),getDate(),120) 2005-11-18 10:20
select convert(varchar,datepart(minute,getdate())) 获得分钟且转换为字符型
内联结/外联结
--返回两个表中共有的所有记录
select *
from testTable as a
inner join TestTableChild as b on a.id = b.parentid
--返回(左表)TestTable所有记录
select *
from testTable as a
left outer join TestTableChild as b on a.id = b.parentid
--返回(右表)TestTableChild的所有记录
select *
from testTable as a
right outer join TestTableChild as b on a.id = b.parentid
--- 返回 两个表里共有的记录,且不重复
select a.id,a.name,b.name
from testTable as a
inner join TestTableChild as b on a.id = b.parentid
group by a.id,a.name,b.name
--返回(左表)TestTable所有记录
select a.id,a.name,b.name
from testTable as a
left outer join TestTableChild as b on a.id = b.parentid
group by a.id,a.name,b.name
--------
select a.id,a.subject,b.contentType,c.AuguryUp,c.AuguryDown,
case c.type when '1' then '爱情' when '2' then '财运' when '3' then '事业' end as type
from MMS_Content as a
left outer Join MMS_ContentChild as b on a.id = b.parentid
left outer join AuguryList as c on a.id = c.parentid
where a.dept = 6
group by a.id,a.subject,b.contentType,c.AuguryUp,c.augurydown,c.type
向一个表A中插入记录,并且插入的记录在A中不存在(通过一个字段来判断)
insert into trace_users (tracekey,muteSMS,CreateTime,traceuser,tracetime,traceSlot,traceduration)
select 'TRACE_TIMER',0,getdate(),mobileid,getdate(),'30','0'
from Epm_EmployeeList where corpid = 10001
and mobileid not in (select traceuser from trace_users )
and mobileid like '13%' and len(mobileid) = 11
下面的要好些(not exists)
insert into trace_users (tracekey,muteSMS,CreateTime,traceuser,tracetime,traceSlot,traceduration)
select 'TRACE_TIMER',0,getdate(),mobileid,getdate(),'30','0'
from Epm_EmployeeList where corpid = 10001
and not exists (select traceuser from trace_users )
and mobileid like '13%' and len(mobileid) = 11
cast 和convert DateAdd和DateDiff
-- 调度设置的时候更新人员状态
--EPM_EmployeeList 里的active = 1
--trace_Timer 里的active = 1
--trace_users 里的traceduration 清0
--执行例子:exec up_SetSchedule 1001,'1009,1019'
ALTER proc up_SetSchedule
--create proc up_SetSchedule
@nCorpId int,
@vchEmployeeIds varchar(8000),
@TimeStart DateTime,
@TimeEnd DateTime
as
declare @sql varchar(8000),@TraceSolt int
SET XACT_ABORT ON --任何一部有问题是都会回滚事务
BEGIN TRANSACTION --开始事务
update EPM_EmployeeList set activeStatus = 0 where corpid = @nCorpId and activeStatus != 0
if (@vchEmployeeIds !='')
begin
set @sql ='update EPM_EmployeeList set activeStatus = 1 where corpid= '+convert(varchar(10),@nCorpId)+ ' and id in ('+@vchEmployeeIds+')'
exec (@sql)
--更新Trace_timer
set @sql ='update trace_Timer set activeStatus = 1 where corpid= '+convert(varchar(10),@nCorpId)+ ' and mobileid in ('
set @sql= @sql+'select mobileid from EPM_EmployeeList where id in ('+@vchEmployeeIds+'))'
exec (@sql)
select @TraceSolt = (select tracesolt from EPM_EnterpriseList where id = @nCorpId)
('+@vchEmployeeIds+'))'
set @sql ='update trace_users set createTime ='''+cast(@timeStart as varchar)+''''
set @sql= @sql+',traceTime='''+cast(DateAdd(minute,@TraceSolt,@timeStart) as varchar )
set @sql= @sql+''',traceDuration ='''+convert(varchar,datediff(minute,@timeStart,@timeEnd))+''' where traceuser in ('
set @sql= @sql+'select mobileid from EPM_EmployeeList where id in ('+@vchEmployeeIds+'))'
exec (@sql)
end
COMMIT TRANSACTION --提交事务
GO