--IF ELSE declare @x int @y int @z int select @x = 1 @y = 2 @z=3 if @x > @y print ‘x > y‘ --打印字符串‘x > y‘ else if @y > @z print ‘y > z‘ else print ‘z > y‘
--CASE use pangu update employee set e_wage = case when job_level = ’1’ then e_wage*1.08 when job_level = ’2’ then e_wage*1.07 when job_level = ’3’ then e_wage*1.06 else e_wage*1.05 end
--WHILE CONTINUE BREAK declare @x int @y int @c int select @x = 1 @y=1 while @x < 3 begin print @x --打印变量x 的值 while @y < 3 begin select @c = 100*@x + @y print @c --打印变量c 的值 select @y = @y + 1 end select @x = @x + 1 select @y = 1 end
--WAITFOR --例 等待1 小时2 分零3 秒后才执行SELECT 语句 waitfor delay ’01:02:03’ select * from employee --例 等到晚上11 点零8 分后才执行SELECT 语句 waitfor time ’23:08:00’ select * from employee
***SELECT***
select *(列名) from table_name(表名) where column_name operator value ex:(宿主) select * from stock_information where stockid = str(nid) stockname = ‘str_name‘ stockname like ‘% find this %‘ stockname like ‘[a-zA-Z]%‘ --------- ([]指定值的范围) stockname like ‘[^F-M]%‘ --------- (^排除指定范围) --------- 只能在使用like关键字的where子句中使用通配符) or stockpath = ‘stock_path‘ or stocknumber < 1000 and stockindex = 24 not stock*** = ‘man‘ stocknumber between 20 and 100 stocknumber in(10,20,30) order by stockid desc(asc) --------- 排序,desc-降序,asc-升序 order by 1,2 --------- by列号 stockname = (select stockname from stock_information where stockid = 4) --------- 子查询 --------- 除非能确保内层select只返回一个行的值, --------- 否则应在外层where子句中用一个in限定符 select distinct column_name form table_name --------- distinct指定检索独有的列值,不重复 select stocknumber ,"stocknumber + 10" = stocknumber + 10 from table_name select stockname , "stocknumber" = count(*) from table_name group by stockname --------- group by 将表按行分组,指定列中有相同的值 having count(*) = 2 --------- having选定指定的组 select * from table1, table2 where table1.id *= table2.id -------- 左外部连接,table1中有的而table2中没有得以null表示 table1.id =* table2.id -------- 右外部连接
select stockname from table1 union [all] ----- union合并查询结果集,all-保留重复行 select stockname from table2
***insert***
insert into table_name (Stock_name,Stock_number) value ("xxx","xxxx") value (select Stockname , Stocknumber from Stock_table2)---value为select语句
----系统函数---- APP_NAME() --函数返回当前执行的应用程序的名称 COALESCE() --函数返回众多表达式中第一个非NULL 表达式的值 COL_LENGTH(<‘table_name‘>, <‘column_name‘>) --函数返回表中指定字段的长度值 COL_NAME(, ) --函数返回表中指定字段的名称即列名 DATALENGTH() --函数返回数据表达式的数据的实际长度 DB_ID([‘database_name‘]) --函数返回数据库的编号 DB_NAME(database_id) --函数返回数据库的名称 HOST_ID() --函数返回服务器端计算机的名称 HOST_NAME() --函数返回服务器端计算机的名称 IDENTITY([, seed increment]) [AS column_name]) --IDENTITY() 函数只在SELECT INTO 语句中使用用于插入一个identity column列到新表中 /*select identity(int, 1, 1) as column_name into newtable from oldtable*/ ISDATE() --函数判断所给定的表达式是否为合理日期 ISNULL(, ) --函数将表达式中的NULL 值用指定值替换 ISNUMERIC() --函数判断所给定的表达式是否为合理的数值 NEWID() --函数返回一个UNIQUEIDENTIFIER 类型的数值 NULLIF(, ) --NULLIF 函数在expression1 与expression2 相等时返回NULL 值若不相等时则返回expression1 的值 精妙SQL语句 说明:复制表(只复制结构,源表名:a 新表名:b) SQL: select * into b from a where 1<>1 说明:拷贝表(拷贝数据,源表名:a 目标表名:b) SQL: insert into b(a, b, c) select d,e,f from b; 说明:显示文章、提交人和最后回复时间 SQL: select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b 说明:外连接查询(表名1:a 表名2:b) SQL: select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c 说明:日程安排提前五分钟提醒 SQL: select * from 日程安排 where datediff(‘minute‘,f开始时间,getdate())>5
说明:两张关联表,删除主表中已经在副表中没有的信息 SQL: delete from info where not exists ( select * from infobz where info.infid=infobz.infid ) 说明:-- SQL: SELECT A.NUM, A.NAME, B.UPD_DATE, B.PREV_UPD_DATE FROM TABLE1, (SELECT X.NUM, X.UPD_DATE, Y.UPD_DATE PREV_UPD_DATE FROM (SELECT NUM, UPD_DATE, INBOUND_QTY, STOCK_ONHAND FROM TABLE2 WHERE TO_CHAR(UPD_DATE,‘YYYY/MM‘) = TO_CHAR(SYSDATE, ‘YYYY/MM‘)) X, (SELECT NUM, UPD_DATE, STOCK_ONHAND FROM TABLE2 WHERE TO_CHAR(UPD_DATE,‘YYYY/MM‘) = TO_CHAR(TO_DATE(TO_CHAR(SYSDATE, ‘YYYY/MM‘) || ‘/01‘,‘YYYY/MM/DD‘) - 1, ‘YYYY/MM‘) ) Y, WHERE X.NUM = Y.NUM (+) AND X.INBOUND_QTY + NVL(Y.STOCK_ONHAND,0) <> X.STOCK_ONHAND ) B WHERE A.NUM = B.NUM 说明:-- SQL: select * from studentinfo where not exists (select * from student where studentinfo.id=student.id) and 系名称=‘"& strdepartmentname&"‘ and 专业名称=‘"&strprofessionname& "‘ order by 性别,生源地,高考总成绩 说明: 从数据库中去一年的各单位电话费统计(电话费定额贺电化肥清单两个表来源) SQL: SELECT a.userper, a.tel, a.standfee, TO_CHAR(a.telfeedate, ‘yyyy‘) AS telyear, SUM(decode(TO_CHAR(a.telfeedate, ‘mm‘), ‘01‘, a.factration)) AS JAN, SUM(decode(TO_CHAR(a.telfeedate, ‘mm‘), ‘02‘, a.factration)) AS FRI, SUM(decode(TO_CHAR(a.telfeedate, ‘mm‘), ‘03‘, a.factration)) AS MAR, SUM(decode(TO_CHAR(a.telfeedate, ‘mm‘), ‘04‘, a.factration)) AS APR, SUM(decode(TO_CHAR(a.telfeedate, ‘mm‘), ‘05‘, a.factration)) AS MAY, SUM(decode(TO_CHAR(a.telfeedate, ‘mm‘), ‘06‘, a.factration)) AS JUE, SUM(decode(TO_CHAR(a.telfeedate, ‘mm‘), ‘07‘, a.factration)) AS JUL, SUM(decode(TO_CHAR(a.telfeedate, ‘mm‘), ‘08‘, a.factration)) AS AGU, SUM(decode(TO_CHAR(a.telfeedate, ‘mm‘), ‘09‘, a.factration)) AS SEP, SUM(decode(TO_CHAR(a.telfeedate, ‘mm‘), ‘10‘, a.factration)) AS OCT, SUM(decode(TO_CHAR(a.telfeedate, ‘mm‘), ‘11‘, a.factration)) AS NOV, SUM(decode(TO_CHAR(a.telfeedate, ‘mm‘), ‘12‘, a.factration)) AS DEC FROM (SELECT a.userper, a.tel, a.standfee, b.telfeedate, b.factration FROM TELFEESTAND a, TELFEE b WHERE a.tel = b.telfax) a GROUP BY a.userper, a.tel, a.standfee, TO_CHAR(a.telfeedate, ‘yyyy‘) 说明:四表联查问题: SQL: select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where ..... 说明:得到表中最小的未使用的ID号 SQL: SELECT (CASE WHEN EXISTS(SELECT * FROM Handle b WHERE b.HandleID = 1) THEN MIN(HandleID) + 1 ELSE 1 END) as HandleID FROM Handle WHERE NOT HandleID IN (SELECT a.HandleID - 1 FROM Handle a)
自连接取出荣于数据 把所有姓名相同的只取出一个 select a.name from table_name a where a.id in (select b.id from table_name b where a.id<>b.id) 同理删除荣誉数据 delete from table_name where table_name.id in (select b.id from table_name b where table_name.id<>b.id)
SELECT DISTINCT TSD.Time_Sheet_Dtl_Record_No,TSD.User_Record_No,TP.Period_Start_Date ,TP.Period_End_Date INTO #temp FROM Time_Sheet_Details TSD, Time_Sheet_Period TP ,User_Group_User_Relationship UGUR,User_Group_Master UGM ,User_Data_Access_Right UDAR WHERE TSD.status =‘TS_WFMGRA‘ AND DATEDIFF(dd,TP.period_start_date,TSD.work_Date)>=0 AND DATEDIFF(dd,TP.period_end_date,TSD.work_Date)<=0 AND UGUR.User_Record_No = TSD.User_Record_No AND UGM.User_Group_Record_No=UGUR.User_Group_Record_No AND UGM.User_Group_Name IN(‘Technician‘,‘Engineer‘) AND UDAR.User_Record_No = TSD.User_Record_No AND UDAR.Division_Record_No IN(1) SELECT DISTINCT A.User_Record_No, B.Staff_No, B.Full_Name,B.Job_Title, SUM(working_hour) AS Working_Hours,SUM(ot) AS OT_HOURS, C.Period_Start_Date,C.Period_End_Date INTO #temp2 FROM Time_Sheet_Details A INNER JOIN User_Master B ON B.User_Record_No= A.User_Record_No INNER JOIN #temp C ON C.Time_Sheet_Dtl_Record_No = A.Time_Sheet_Dtl_Record_No GROUP BY A.User_Record_No, B.Staff_No,B.Full_Name,B.Job_Title, C.Period_Start_Date,C.Period_End_Date HAVING COUNT(*) = DATEDIFF(d,C.Period_Start_Date,C.Period_End_Date)+1 Select A.User_Record_No,A.Staff_No,A.Full_Name,A.Job_Title ,A.Working_Hours,A.OT_HOURS,A.Period_Start_Date,A.Period_End_Date ,DM.Division_Code INTO #temp3 FROM #temp2 AS A INNER JOIN User_Data_Access_Right UDAR ON UDAR.User_Record_No = A.User_Record_No INNER JOIN Division_Master DM ON DM.Division_Record_No = UDAR.Division_Record_No SELECT * From #temp3 order by 1,7,8; Select Count(Distinct User_Record_No+Period_Start_Date+Period_End_Date) From #temp3 DROP TABLE #temp ,#temp2,#temp3
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b) 选择在每一组b值相同的数据中对应的a最大的(换成average或别的函数或子查询,你会有意想不到的发现)记录的所有信息. 类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等. 上面的许多同志对子查询存在有偏见与误解,其实在一个好的数据分析程序中,子查询可以简化很多程序逻辑.
获益不浅啊. SELECT DISTINCT TSD.Time_Sheet_Dtl_Record_No,TSD.User_Record_No,TP.Period_Start_Date ,TP.Period_End_Date INTO #temp FROM Time_Sheet_Details TSD, Time_Sheet_Period TP ,User_Group_User_Relationship UGUR,User_Group_Master UGM ,User_Data_Access_Right UDAR WHERE TSD.status =‘TS_WFMGRA‘ AND DATEDIFF(dd,TP.period_start_date,TSD.work_Date)>=0 AND DATEDIFF(dd,TP.period_end_date,TSD.work_Date)<=0 AND UGUR.User_Record_No = TSD.User_Record_No AND UGM.User_Group_Record_No=UGUR.User_Group_Record_No AND UGM.User_Group_Name IN(‘Technician‘,‘Engineer‘) AND UDAR.User_Record_No = TSD.User_Record_No AND UDAR.Division_Record_No IN(1) SELECT DISTINCT A.User_Record_No, B.Staff_No, B.Full_Name,B.Job_Title, SUM(working_hour) AS Working_Hours,SUM(ot) AS OT_HOURS, C.Period_Start_Date,C.Period_End_Date INTO #temp2 FROM Time_Sheet_Details A INNER JOIN User_Master B ON B.User_Record_No= A.User_Record_No INNER JOIN #temp C ON C.Time_Sheet_Dtl_Record_No = A.Time_Sheet_Dtl_Record_No GROUP BY A.User_Record_No, B.Staff_No,B.Full_Name,B.Job_Title, C.Period_Start_Date,C.Period_End_Date HAVING COUNT(*) = DATEDIFF(d,C.Period_Start_Date,C.Period_End_Date)+1 Select A.User_Record_No,A.Staff_No,A.Full_Name,A.Job_Title ,A.Working_Hours,A.OT_HOURS,A.Period_Start_Date,A.Period_End_Date ,DM.Division_Code INTO #temp3 FROM #temp2 AS A INNER JOIN User_Data_Access_Right UDAR ON UDAR.User_Record_No = A.User_Record_No INNER JOIN Division_Master DM ON DM.Division_Record_No = UDAR.Division_Record_No SELECT * From #temp3 order by 1,7,8; Select Count(Distinct User_Record_No+Period_Start_Date+Period_End_Date) From #temp3 DROP TABLE #temp ,#temp2,#temp3 :) cpp2017(长安不见使人愁)这么长一句,少见,能否介绍介绍它的功力?^_^ SELECT DISTINCT TSD.Time_Sheet_Dtl_Record_No,TSD.User_Record_No,TP.Period_Start_Date ,TP.Period_End_Date INTO #temp FROM Time_Sheet_Details TSD, Time_Sheet_Period TP ,User_Group_User_Relationship UGUR,User_Group_Master UGM ,User_Data_Access_Right UDAR WHERE TSD.status =‘TS_WFMGRA‘ AND DATEDIFF(dd,TP.period_start_date,TSD.work_Date)>=0 AND DATEDIFF(dd,TP.period_end_date,TSD.work_Date)<=0 AND UGUR.User_Record_No = TSD.User_Record_No AND UGM.User_Group_Record_No=UGUR.User_Group_Record_No AND UGM.User_Group_Name IN(‘Technician‘,‘Engineer‘) AND UDAR.User_Record_No = TSD.User_Record_No AND UDAR.Division_Record_No IN(1) SELECT DISTINCT A.User_Record_No, B.Staff_No, B.Full_Name,B.Job_Title, SUM(working_hour) AS Working_Hours,SUM(ot) AS OT_HOURS, C.Period_Start_Date,C.Period_End_Date INTO #temp2 FROM Time_Sheet_Details A INNER JOIN User_Master B ON B.User_Record_No= A.User_Record_No INNER JOIN #temp C ON C.Time_Sheet_Dtl_Record_No = A.Time_Sheet_Dtl_Record_No GROUP BY A.User_Record_No, B.Staff_No,B.Full_Name,B.Job_Title, C.Period_Start_Date,C.Period_End_Date HAVING COUNT(*) = DATEDIFF(d,C.Period_Start_Date,C.Period_End_Date)+1 Select A.User_Record_No,A.Staff_No,A.Full_Name,A.Job_Title ,A.Working_Hours,A.OT_HOURS,A.Period_Start_Date,A.Period_End_Date ,DM.Division_Code INTO #temp3 FROM #temp2 AS A INNER JOIN User_Data_Access_Right UDAR ON UDAR.User_Record_No = A.User_Record_No INNER JOIN Division_Master DM ON DM.Division_Record_No = UDAR.Division_Record_No SELECT * From #temp3 order by 1,7,8; Select Count(Distinct User_Record_No+Period_Start_Date+Period_End_Date) From #temp3 DROP TABLE #temp ,#temp2,#temp3
pwdencrypt 密码加密? 有些什么作用,不明白 随机取出10条数据 select top 10 * from tablename order by newid()
功能: type vender pcs 电脑 A 1 电脑 A 1 光盘 B 2 光盘 A 2 手机 B 3 手机 C 3 select type,sum(case vender when ‘A‘ then pcs else 0 end),sum(case vender when ‘C‘ then pcs else 0 end),sum(case vender when ‘B‘ then pcs else 0 end) FROM tablename group by type
常识补充 统计函数: AVG(字段名) 得出一个表格栏平均值 COUNT(*|字段名) 对数据行数的统计或对某一栏有值的数据行数统计 MAX(字段名) 取得一个表格栏最大的值 MIN(字段名) 取得一个表格栏最小的值 SUM(字段名) 把数据栏的值相加 eg: sql="select sum(字段名) as 别名 from 数据表 where 条件表达式"
select name from sysobjects where type=‘U‘‘列出数据库里所有的表名 select name from syscolumns where id=object_id(‘TableName‘)‘列出表里的所有的
source data kzx4dm xbdm jylsfsdm ... 11 2 10 11 2 10 12 2 10 12 1 20 12 1 20 destination: kzx4dm bys_count yjs_count jy_ratio 11 2 2 1.00 12 3 1 1/3 SELECT DISTINCT kzx4dm,(SELECT COUNT(jylsfsdm) FROM tablename WHERE kzx4dm=TA.kzx4dm) AS bys_count,(SELECT COUNT(jylsfsdm) FROM tablename WHERE kzx4dm=TA.kzx4dm WHERE jylsfsdm=10) AS yjs_count,yjs_count/bys_count AS jy_ratio FROM tablename AS TA
SELECT DISTINCT kzx4dm,(SELECT COUNT(jylsfsdm) FROM tablename WHERE kzx4dm=TA.kzx4dm) AS bys_count,(SELECT COUNT(jylsfsdm) FROM tablename WHERE kzx4dm=TA.kzx4dm AND jylsfsdm=10) AS yjs_count,yjs_count/bys_count AS jy_ratio FROM tablename AS TA
二维表 T(F1,F2,F3,F4,F5,F6,F7) 表示如下关系: 学生ID 学生姓名 课程ID 课程名称 成绩 教师ID 教师姓名 S3 王五 K4 政治 53 T4 赵老师 S1 张三 K1 数学 61 T1 张老师 S2 李四 K3 英语 88 T3 李老师 S1 张三 K4 政治 77 T4 赵老师 S2 李四 K4 政治 67 T5 周老师 S3 王五 K2 语文 90 T2 王老师 S3 王五 K1 数学 55 T1 张老师 S1 张三 K2 语文 81 T2 王老师 S4 赵六 K2 语文 59 T1 王老师 S1 张三 K3 英语 37 T3 李老师 S2 李四 K1 数学 81 T1 张老师 请以一句 T-SQL (Ms SQL Server) 或 Jet SQL (Ms Access) 在 原表 T 基础上作答 1.如果 T 表还有一字段 F0 数据类型为自动增量整型(唯一,不会重复), 而且 T 表中含有除 F0 字段外,请删除其它字段完全相同的重复多余的脏记录数据: delete from t where f0 in(select max(f0) from t group by f1,f2,f3,f4,f5,f6,f7 having count(f0)>1) 2.列印各科成绩最高和最低的记录: (就是各门课程的最高、最低分的学生和老师) 课程ID,课程名称,最高分,学生ID,学生姓名,教师ID,教师姓名,最低分,学生ID,学生姓名,教师ID,教师姓名 select tb.f4,tb.f3,tb1.f5,tb.f1,tb.f2,tb.f6,tb.f7,tb2.f5,tb2.f1,tb2.f2,tb2.f6,tb2.f7 from t tb where f5=(select max(f5) from t where t.f4=tb.f4) join select f2,f7 from t tb2 where f5=(select min(f5) from t where t.f4=tb2.f4) on tb.f4=tb2.f4 先完成一个,想想在做下一个. 3.按成绩从高到低顺序,列印所有学生四门(数学,语文,英语,政治)课程成绩: (就是每个学生的四门课程的成绩单) 学生ID,学生姓名,数学,语文,英语,政治,有效课程数,有效平均分 (注: 有效课程即在 T 表中有该学生的成绩记录,如不明白可不列印"有效课程数"和"有效平均分") select tb1.f1,tb1.f2,count(tb1.f5) as scores,sum(tb1.f5) as scoresum, avg(tb1.f5) AS average, tb2.f5,tb3.f5,tb4.f5,tb5.f5 from t as tb1 left join t as tb2 on tb1.f0=tb2.f0 and tb2.f3=k4 left join t as tb3 on tb1.f0=tb3.f0 and tb3.f3=k3 left join t as tb4 on tb1.f0=tb4.f0 and tb4.f3=k2 left join t as tb5 on tb1.f0=tb5.f0 and tb5.f3=k1 grout by tb1.f2 order by tb1.scoresum desc 4.按各科不及格率的百分数从低到高和平均成绩从高到低顺序,统计并列印各科平均成绩和不及格率的百分数(用"N行"表示): (就是分析哪门课程难) 课程ID,课程名称,平均成绩,及格百分数 select f3,f4, (select count(f1) from t where t.f4=tb.f4 and f5<60)/(select count(f1) from t where t.f4=tb.f4) as failper,((select sum(f5) from t where t.f4=tb.f4)/ (select count(f5) from t where t.f4=tb.f4)) as averagescore from t tb order by failper asc, as averagescore desc
/****** Object: Stored Procedure dbo.dt_checkoutobject Script Date: 2003-3-12 9:25:26 ******/ create proc dbo.dt_checkoutobject @chObjectType char(4), @vchObjectName varchar(255), @vchComment varchar(255), @vchLoginName varchar(255), @vchPassword varchar(255), @iVCSFlags int = 0, @iActionFlag int = 0/* 0 => Checkout, 1 => GetLatest, 2 => UndoCheckOut */ as set nocount on declare @iReturn int declare @iObjectId int select @iObjectId =0 declare @VSSGUID varchar(100) select @VSSGUID = ‘SQLVersionControl.VCS_SQL‘ declare @iReturnValue int select @iReturnValue = 0 declare @vchTempText varchar(255) /* this is for our strings */ declare @iStreamObjectId int select @iStreamObjectId = 0 declare @iPropertyObjectId int select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = ‘VCSProjectID‘) declare @vchProjectName varchar(255) declare @vchSourceSafeINI varchar(255) declare @vchServerName varchar(255) declare @vchDatabaseName varchar(255) exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, ‘VCSProject‘, @vchProjectName OUT exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, ‘VCSSourceSafeINI‘, @vchSourceSafeINI OUT exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, ‘VCSSQLServer‘, @vchServerName OUT exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, ‘VCSSQLDatabase‘, @vchDatabaseName OUT if @chObjectType = ‘PROC‘ begin /* Procedure Can have up to three streams Drop Stream, Create Stream, GRANT stream */ exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT if @iReturn <> 0 GOTO E_OAError exec @iReturn = sp_OAMethod @iObjectId, ‘CheckOut_StoredProcedure‘, NULL, @sProjectName = @vchProjectName, @sSourceSafeINI = @vchSourceSafeINI, @sObjectName = @vchObjectName, @sServerName = @vchServerName, @sDatabaseName = @vchDatabaseName, @sComment = @vchComment, @sLoginName = @vchLoginName, @sPassword = @vchPassword, @iVCSFlags = @iVCSFlags, @iActionFlag = @iActionFlag if @iReturn <> 0 GOTO E_OAError exec @iReturn = sp_OAGetProperty @iObjectId, ‘GetStreamObject‘, @iStreamObjectId OUT if @iReturn <> 0 GOTO E_OAError create table #commenttext (id int identity, sourcecode varchar(255)) select @vchTempText = ‘STUB‘ while @vchTempText IS NOT NULL begin exec @iReturn = sp_OAMethod @iStreamObjectId, ‘GetStream‘, @iReturnValue OUT, @vchTempText OUT if @iReturn <> 0 GOTO E_OAError if (@vchTempText IS NOT NULL) insert into #commenttext (sourcecode) select @vchTempText end select ‘VCS‘=sourcecode from #commenttext order by id select ‘SQL‘=text from syscomments where id = object_id(@vchObjectName) order by colid end CleanUp: return E_OAError: exec dbo.dt_displayoaerror @iObjectId, @iReturn GOTO CleanUp GO
1.如果 T 表还有一字段 F0 数据类型为自动增量整型(唯一,不会重复), 而且 T 表中含有除 F0 字段外,请删除其它字段完全相同的重复多余的脏记录数据: delete from t where f0 in(select max(f0) from t group by f1,f2,f3,f4,f5,f6,f7 having count(f0)>1) 上面这个sql有问题 正确的如下 DELETE Legal_Dispute_Lawyer WHERE Lawyer_Record_No IN(SELECT Lawyer_Record_No FROM Legal_Dispute_Lawyer LDL WHERE Lawyer_Record_No(SELECT TOP 1 Lawyer_Record_No FROM Legal_Dispute_Lawyer WHERE LD=LDL.LD AND Name=LDL.Name AND Email=LDL.Email AND Phone_No=LDL.Phone_No AND Fax_No=LDL.Fax_No)) 消除Legal_Dispute_Lawyer 表中除Lawyer_Record_No(自增字段)外其余数据完全相同的记录. 表结构如下 if exists (select * from dbo.sysobjects where id = object_id(N‘[dbo].[Legal_Dispute_Lawyer]‘) and OBJECTPROPERTY(id, N‘IsUserTable‘) = 1) drop table [dbo].[Legal_Dispute_Lawyer] GO CREATE TABLE [dbo].[Legal_Dispute_Lawyer] ( [Lawyer_Record_No] [int] IDENTITY (1, 1) NOT NULL , [LD] [int] NOT NULL , [Name] [int] NOT NULL , [Phone_No] [varchar] (255) COLLATE Chinese_PRC_CI_AS NULL , [Fax_No] [varchar] (255) COLLATE Chinese_PRC_CI_AS NULL , [varchar] (255) COLLATE Chinese_PRC_CI_AS NULL ) ON [PRIMARY] GO 以这种方式还可以实现组内消除重复值..
Top
DELETE Legal_Dispute_Lawyer WHERE Lawyer_Record_No IN(SELECT Lawyer_Record_No FROM Legal_Dispute_Lawyer LDL WHERE Lawyer_Record_No<>(SELECT TOP 1 Lawyer_Record_No FROM Legal_Dispute_Lawyer WHERE LD=LDL.LD AND Name=LDL.Name AND Email=LDL.Email AND Phone_No=LDL.Phone_No AND Fax_No=LDL.Fax_No))
create table IKnowYou (userid varchar(30), TableName varchar(50), Action varchar(6), DateT datatime, TrrigerTableColumns....., TrrigerTableColumns.....) create trriger Who_Do_It on table for update as declare userid varchar(30) declare TableName varchar(50) declare Action varchar(6) userid=@@suser_sname Action=‘update‘ TableName=‘tabel‘ insert into IKnowYou values(userid,TableName,Action,Now,select * from deleted,select * from inserted)
kill all connections to a given databse CREATE PROCEDURE usp_killDBConnections @DBName varchar(50), @withmsg bit=1 AS SET NOCOUNT ON DECLARE @spidstr varchar(8000) DECLARE @ConnKilled smallint SET @ConnKilled=0 SET @spidstr = ‘‘ IF db_id(@DBName) < 4 BEGIN PRINT ‘Connections to system databases cannot be killed‘ RETURN END SELECT @spidstr=coalesce(@spidstr,‘,‘ )+‘kill ‘+convert(varchar, spid)+ ‘; ‘ FROM master..sysprocesses WHERE dbid=db_id(@DBName) IF LEN(@spidstr) > 0 BEGIN EXEC(@spidstr) SELECT @ConnKilled = COUNT(1) FROM master..sysprocesses WHERE dbid=db_id(@DBName) END IF @withmsg =1 PRINT CONVERT(VARCHAR(10), @ConnKilled) + ‘ Connection(s) killed for DB ‘ + @DBName GO
SELECT A.NUM, A.NAME, B.UPD_DATE, B.PREV_UPD_DATE FROM TABLE1, (SELECT X.NUM, X.UPD_DATE, Y.UPD_DATE PREV_UPD_DATE FROM (SELECT NUM, UPD_DATE, INBOUND_QTY, STOCK_ONHAND FROM TABLE2 WHERE TO_CHAR(UPD_DATE,‘YYYY/MM‘) = TO_CHAR(SYSDATE, ‘YYYY/MM‘)) X, (SELECT NUM, UPD_DATE, STOCK_ONHAND FROM TABLE2 WHERE TO_CHAR(UPD_DATE,‘YYYY/MM‘) = TO_CHAR(TO_DATE(TO_CHAR(SYSDATE, ‘YYYY/MM‘) ¦¦ ‘/01‘,‘YYYY/MM/DD‘) - 1, ‘YYYY/MM‘) ) Y, WHERE X.NUM = Y.NUM (+) AND X.INBOUND_QTY + NVL(Y.STOCK_ONHAND,0) <> X.STOCK_ONHAND ) B WHERE A.NUM = B.NUM
SELECT * FROM table ORDER BY id SELECT * FROM table ORDER BY id DESC 正反排序,厉害吧!
select * into b from a where 1<>1 这样生成的b表访问的用户没有select的权限? 请问sql DX们这个问题怎么解决?
Select left(field,1) as field1 from table_name order by field desc
select count(clubmember.clubid)as hot,clubmember.clubid,clubinfo.clubid,clubinfo.name from clubmember,clubinfo where clubinfo.clubid=clubmember.clubid group by clubmember.clubid order by hot DESC limit 10
条件删除 DELETE DBO.TEMP WHERE FLD_CHARACTER IN ( SELECT FLD_CHARACTER FROM dbo.TBL_CHARACTER WHERE (FLD_DELETED = 1) AND (FLD_LEVEL <= 18) AND (FLD_UPDATEDATETIME <= GETDATE() - 5) )
选择前数据库里前10条记录: 1、select top 10 * from table 2、set rowcount 10 select * from table
今天才把合计函数搞定: Set rs=conn.execute("Select min(id) as minID from TABLE") ^_^
select * from 日程安排 where datediff(‘minute‘,f开始时间,getdate())>5 日程安排提前五分钟提醒。
select * into b from a where 1<>1 这样生成的b表访问的用户没有select的权限? 请问sql DX们这个问题怎么解决? 指定dbo前缀应该可以解决问题了..
mark!
<% ‘取出随机记录 Randomize RNumber = Int(Rnd*200) + 1 SQL = "SELECT * FROM Customers WHERE ID = " & RNumber set objRec = ObjConn.Execute(SQL) Response.WriteRNumber & " = " & objRec("ID") & " " & objRec("c_email") %>
insert into pbrule(newrid,subj,bz,zf,orid,rstat,layer,bid) select newrid,subj,bz,zf,orid,rstat,layer,bid from pbrule1 where bruleid=bruleid 将pbrule1 表中符合条件的记录 导入 pbrule表中
下面这个更实用,就是两张关联表,删除主表中已经在副表中没有的信息 delete from info where not exists ( select * from infobz where info.infid=infobz.infid ) 这条语句就是删除 INFO表中infid字段在infobz中不存在的记录 此语句用来维护数据库很有用哦。 楼主给点分吧
CREATE OR REPLACE PROCEDURE DUMP_TO_WEB_TCLHD_SP_OBJ AS BEGIN CALC_PIA_PRICE ; DELETE FROM TCLHD_SP_OBJ ; INSERT INTO TCLHD_SP_OBJ (NAME,CODE,ID,PRICE,TYPE,FIELDS) ( SELECT c.DESCRIPTION,C.SEGMENT1,a.INVENTORY_ITEM_ID, nvl(c.ATTRIBUTE14,‘0‘),0,nvl(c.ATTRIBUTE13,0) from mtl_item_categories a , mtl_categories b , mtl_system_items c where a.CATEGORY_ID = b.CATEGORY_ID and b.SEGMENT1=‘原材料‘ and a.INVENTORY_ITEM_ID = c.INVENTORY_ITEM_ID AND A.ORGANIZATION_ID = 21 and c.ORGANIZATION_ID = 21 and c.inventory_item_status_code = ‘Active‘ ); COMMIT ; END ;
数据库IBM DB2 》》》SQL 绝对精华 select dmbh,SJDM,flsm,dmzz from ydm where dmbh=3300 union all select dmbh,SJDM,flsm,dmzz from ydm where dmbh in (select dmzz from ydm where dmbh=3300) union all select dmbh,SJDM,flsm,dmzz from ydm where dmbh in (select dmzz from ydm where dmbh in ( select dmzz from ydm where dmbh=3300)) union all select dmbh,SJDM,flsm,dmzz from ydm where dmbh in (select dmzz from ydm where dmbh in (select dmzz from ydm where dmbh in ( select dmzz from ydm where dmbh=3300))) union all select dmbh,SJDM,flsm,dmzz from ydm where dmbh in (select dmzz from ydm where dmbh in (select dmzz from ydm where dmbh in (select dmzz from ydm where dmbh in ( select dmzz from ydm where dmbh=3300)))) ********************************** select SJDM from ydm where dmbh=3300 union all select SJDM from ydm where dmbh in (select dmzz from ydm where dmbh=3300) union all select SJDM from ydm where dmbh in (select dmzz from ydm where dmbh in ( select dmzz from ydm where dmbh=3300)) union all select SJDM from ydm where dmbh in (select dmzz from ydm where dmbh in (select dmzz from ydm where dmbh in ( select dmzz from ydm where dmbh=3300))) union all select SJDM from ydm where dmbh in (select dmzz from ydm where dmbh in (select dmzz from ydm where dmbh in (select dmzz from ydm where dmbh in ( select dmzz from ydm where dmbh=3300)))) ************************************************** SELECT COUNT(*) as yhs ,SUM(DF) as df FROM DB2.DFTDF WHERE (year(rq)*12+month(rq)) between 24015 and 24015 AND dflb=513 and (ZHH,YYH) IN (SELECT ZHH,YYxH FROM DB2.YDD111 WHERE HYM in ( select SJDM from DB2.ydm where dmbh=3200 union all select SJDM from DB2.ydm where dmbh in ( select dmzz from DB2.ydm where dmbh=3200) union all select SJDM from DB2.ydm where dmbh in ( select dmzz from DB2.ydm where dmbh in ( select dmzz from DB2.ydm where dmbh=3200)) union all select SJDM from DB2.ydm where dmbh in ( Select dmzz from DB2.ydm where dmbh in ( select dmzz from DB2.ydm where dmbh in ( select dmzz from DB2.ydm where dmbh=3200))) union all select SJDM from DB2.ydm where dmbh in ( select dmzz from DB2.ydm where dmbh in ( select dmzz from DB2.ydm where dmbh in ( select dmzz from DB2.ydm where dmbh in ( select dmzz from DB2.ydm where dmbh=3200)))) )) *********************************************** select bcm,bsm,count(bsm) as sl from ( select bcm,case when blx=‘DXB‘ and bxh like ‘DD%‘ AND BXH NOT LIKE ‘DDS%‘ then ‘JJB‘ else ‘DZB‘ end as bsm from jldb) as jldb2 group by bcm,bsm select bcm,bsm,count(bsm) as sl from ( select bcm,case when blx=‘DXB‘ and bxh like ‘DD%‘ AND BXH NOT LIKE ‘DDS%‘ then ‘JJB‘ else ‘DZB‘ end as bsm from jldb where bzt=‘OK‘ and qyrq between ‘1999-1-1‘ and ‘2003-1-3‘ ) as jldb2 group by bcm,bsm **************** select bcm,bsm,bxh,count(bsm) as sl from ( select bcm,case when blx=‘DXB‘ and bxh like ‘DD%‘ AND BXH NOT LIKE ‘DDS%‘ then ‘JJB‘ else ‘DZB‘ end as bsm,bxh from jldb where bzt=‘OK‘ and qyrq between ‘1999-1-1‘ and ‘2003-1-3‘ ) as jldb2 group by bcm,bxh,bsm ********************************************** with ttt as (select bcm,bxh,bsm,count(bsm) as sl from (select bcm,bxh,case when blx =‘DXB‘ and bxh like ‘DD%‘ AND BXH NOT LIKE ‘DDS%‘ then ‘机械表 ‘ else ‘DZB‘ end as bsm from jldb where bzt=‘OK‘ and qyrq<=‘2002-2-2‘ ) as jldb2 group by bcm,bxh,bsm), sss as (select bcm,bxh,bsm,count(bsm) as sl1 from (select bcm,bxh,case when blx =‘DXB‘ and bxh like ‘DD%‘ AND BXH NOT LIKE ‘DDS%‘ then ‘机械表 ‘ else ‘DZB‘ end as bsm from jldb where bzt=‘OK‘ and qyrq<=‘2000-1-1‘ ) as jldb2 group by bcm,bxh,bsm) select ttt.bcm,ttt.bxh,ttt.bsm,value(ttt.sl,0) as sl1,value(sss.sl1,0) as sl2,(value(ttt.sl,0)-value(sss.sl1,0)) as sl3 from ttt full join sss on sss.bxh=ttt.bxh and sss.bcm=ttt.bcm and sss.bsm=ttt.bsm order by ttt.bcm,ttt.bxh,ttt.bsm
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b) 选择在每一组b值相同的数据中对应的a最大的(换成average或别的函数或子查询,你会有意想不到的发现)记录的所有信息. 类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等. 上面的许多同志对子查询存在有偏见与误解,其实在一个好的数据分析程序中,子查询可以简化很多程序逻辑.
<% ‘取出随机记录 Randomize RNumber = Int(Rnd*200) + 1 SQL = "SELECT * FROM Customers WHERE ID = " & RNumber set objRec = ObjConn.Execute(SQL) Response.WriteRNumber & " = " & objRec("ID") & " " & objRec("c_email") %>
这种方法存在bug,有可能取不出数据来, 最好还是还 select top 1 * from tablename order by newid()
select * from (select top 5 * from (select * from (select top 5 * from GuestBook where 1=1 and Deleted = false order by GuestID desc) order by GuestID asc) order by GuestID asc) order by GuestID desc
select * from (select top 5 * from (select * from (select top 5 * from GuestBook where 1=1 and Deleted = false order by GuestID desc) order by GuestID asc) order by GuestID asc) order by GuestID desc 这可是一个经典的SQL. 大概再加几层嵌套,查询引擎都可以崩溃了..
下面的语句不是精华.但是却是用很多用T-SQL进行开发的同志所不了解的.. 如何更新nText,Text,Image字段数据.. DECLARE @ptrval binary(16) SELECT @ptrval = TEXTPTR(LSD_Comment) FROM Legal_Dispute WHERE LD_Record_No=25 --得到指定记录的nText文本指针 UPDATETEXT Legal_Dispute.LSD_Comment @ptrval 0 0 N‘Insert Text Content Into Old Content Before‘ ---将数据插入在老数据之前. 很多同志在更新nText字段的时候使用一个记录集取回ASP然后一次性用"UPDATE set fieldname=‘" & new content & old content & "‘"的方式实现.. 却不知道,sql string一次只能提交的string是有限制的,这样一来,实际的text,ntext永远也不可能存储它所支持的最大长度的数据..也远远不能达到使用nText字段的目的了