USE WSS_Content SELECT * FROM dbo.utTable32 WHERE DB0461A IN (SELECT DB0461A FROM dbo.utTable32 WHERE ID IN('1','2','2')) ---Row_NUMBER() OVER() SELECT ROW_NUMBER()OVER(ORDER BY ID)AS RowNum,* FROM dbo.utTable32 ---按照id升序排序,并编号。 SELECT ROW_NUMBER()OVER(ORDER BY DB0461A)AS RowNum,* FROM dbo.utTable32 --按照车牌号升序排序并编号。 SELECT ROW_NUMBER()OVER(PARTITION by DB0461A ORDER BY DB0461A)AS RowNum,* FROM dbo.utTable32 --按照车牌号升序排序并编号。 --SELECT ROW_NUMBER()OVER(ORDER BY ID RANGE BETWEEN 2 preceding AND 2 preceding)AS RowNum,* FROM dbo.utTable32 --SELECT DB0461A,DB0923A,SUM(DB0923A)OVER(order by id) AS SS FROM dbo.utTable32 SELECT * FROM dbo.utTable32 WHERE DB0461A LIKE '豫ca%2' SELECT COUNT(*),DB0461A FROM dbo.utTable32 WHERE ID>90 GROUP BY DB0461A SELECT COUNT(*),DB0461A FROM dbo.utTable32 GROUP BY DB0461A HAVING ID>90 SELECT * FROM dbo.utTable23 T23,dbo .utTable24 T24 WHERE T23 .DB0835A =T24 .DB0835A ; SELECT CAST(DB0835A as nvarchar(30))+CAST(DB0836A AS NVARCHAR(30)) FROM dbo.utTable23 SELECT SUBSTRING(DB0835A,8,LEN(DB0835A)-7) FROM dbo.utTable23 --======================游标========================================================== --定义游标 DECLARE UT32_CURSOR CURSOR FOR SELECT ID,DB0002A FROM DBO.UTTABLE32 --打开游标 OPEN UT32_CURSOR --定义变量 DECLARE @ID INT DECLARE @NAME NVARCHAR(40) DECLARE @CLASSid int SELECT @CLASSid =1 --循环移动游标 FETCH NEXT FROM UT32_CURSOR INTO @ID,@NAME WHILE(@@FETCH_STATUS=0) BEGIN IF @CLASSid =12 BEGIN SELECT @CLASSid =1 END SELECT @CLASSid=@CLASSid +1 INSERT INTO dbo.StuTable(ID,StuName,ClassId)VALUES(@ID,@NAME,@CLASSid) FETCH NEXT FROM UT32_CURSOR INTO @ID,@NAME END --关闭游标 CLOSE UT32_CURSOR DEALLOCATE UT32_CURSOR ------------------------------ --随机查询 SELECT * FROM dbo.utTable32 ORDER BY NEWID() select cast( floor(rand(20)*100) as int) SELECT RAND(100)*100,RAND(),RAND() ------------------------------ DECLARE StuTable_CURSOR CURSOR FOR SELECT ID FROM StuTable DECLARE @Age INT DECLARE @UpId INT SELECT @Age =0 OPEN StuTable_CURSOR FETCH NEXT FROM StuTable_CURSOR INTO @UpId WHILE(@@FETCH_STATUS =0) BEGIN SELECT @Age=CAST(FLOOR(RAND()*50) AS INT) WHILE(@Age <20) BEGIN SELECT @Age=CAST(FLOOR(RAND()*50) AS INT) END UPDATE StuTable SET StuAge=CAST(@Age AS NVARCHAR(20)) WHERE ID =@UpId FETCH NEXT FROM StuTable_CURSOR INTO @UpId END CLOSE StuTable_CURSOR DEALLOCATE StuTable_CURSOR ------------------------------- CREATE TABLE #ObjList(ObjName nvarchar(20) not null) INSERT INTO #ObjList VALUES ('语文') INSERT INTO #ObjList VALUES ('数学') INSERT INTO #ObjList VALUES ('英语') INSERT INTO #ObjList VALUES ('化学') INSERT INTO #ObjList VALUES ('物理') INSERT INTO #ObjList VALUES ('生物') DECLARE STUTB_CURSOR CURSOR FOR SELECT ID FROM StuTable DECLARE Obj_CURSOR CURSOR SCROLL FOR SELECT ObjName FROM #ObjList DECLARE @StuId int DECLARE @ObjName nvarchar(20) DECLARE @SID int DECLARE @Score int SELECT @SID =0 SELECT @Score =1 OPEN STUTB_CURSOR OPEN Obj_CURSOR FETCH NEXT FROM STUTB_CURSOR INTO @StuId WHILE(@@FETCH_STATUS =0) BEGIN FETCH NEXT FROM Obj_CURSOR INTO @ObjName IF(@@FETCH_STATUS =-1) BEGIN FETCH FIRST FROM Obj_CURSOR INTO @ObjName --FETCH NEXT FROM Obj_CURSOR INTO @ObjName END WHILE(@@FETCH_STATUS =0) BEGIN SELECT @Score =CAST(FLOOR(RAND()*100) AS INT)+1 SELECT @SID=@SID+1 INSERT INTO ScoreTable (ID,ObjectName,Score,StuId) VALUES (@SID,@ObjName,@Score,@StuId) FETCH NEXT FROM Obj_CURSOR INTO @ObjName END FETCH NEXT FROM STUTB_CURSOR INTO @StuId END CLOSE STUTB_CURSOR CLOSE Obj_CURSOR DEALLOCATE STUTB_CURSOR DEALLOCATE Obj_CURSOR ---------------------------------- DELETE FROM ScoreTable WHERE 1=1 ---------------------------------- ---统计每个班级的人数 SELECT C.ClassName,COUNT(*) AS COUT FROM ClassTable C LEFT JOIN StuTable S ON C.ID =S.ClassId GROUP BY C.ClassName SELECT COUNT(*) AS COUT FROM ClassTable C LEFT JOIN StuTable S ON C.ID =S.ClassId WHERE C.ClassName ='2.2班' ---------------------------------- DECLARE UP_CURSOR CURSOR FOR SELECT C.ClassName,COUNT(*) AS COUT FROM ClassTable C LEFT JOIN StuTable S ON C.ID =S.ClassId GROUP BY C.ClassName DECLARE @Class nvarchar(20) DECLARE @Count INT OPEN UP_CURSOR FETCH NEXT FROM UP_CURSOR INTO @Class,@Count WHILE(@@FETCH_STATUS =0) BEGIN UPDATE dbo.ClassTable SET StuCount =@Count WHERE ClassName =@Class FETCH NEXT FROM UP_CURSOR INTO @Class,@Count END CLOSE UP_CURSOR DEALLOCATE UP_CURSOR ----------------------------------- --统计每个学生各科目成绩和总分 CREATE TABLE #STUSCORE ( ID INT, HX INT, SW INT, SX INT, WL INT, YY INT, YW INT ) ALTER TABLE #STUSCORE ADD ZF INT USE WSS_Content DECLARE STC_CURSOR CURSOR FOR SELECT ID FROM WSS_Content.dbo.StuTable --FOR --read only --WHERE ID BETWEEN 1 AND 200 DECLARE @StudId int OPEN STC_CURSOR FETCH NEXT FROM STC_CURSOR INTO @StudId WHILE(@@FETCH_STATUS =0) BEGIN DECLARE SOC_CURSOR CURSOR SCROLL FOR SELECT ObjectName,Score,StuId FROM WSS_Content.dbo.ScoreTable WHERE StuId=@StudId ORDER BY ObjectName DECLARE @HX INT DECLARE @SW INT DECLARE @SX INT DECLARE @WL INT DECLARE @YY INT DECLARE @YW INT DECLARE @KSFS INT DECLARE @CODE INT DECLARE @KMLX NVARCHAR(20) DECLARE @IDD INT DECLARE @ZF INT OPEN SOC_CURSOR FETCH NEXT FROM SOC_CURSOR INTO @KMLX,@KSFS,@IDD IF @@FETCH_STATUS =-1 BEGIN FETCH FIRST FROM SOC_CURSOR INTO @KMLX,@KSFS,@IDD END WHILE(@@FETCH_STATUS =0) BEGIN IF(@KMLX='语文')BEGIN SELECT @YW=@KSFS END IF(@KMLX='数学')BEGIN SELECT @SX=@KSFS END IF(@KMLX='英语')BEGIN SELECT @YY=@KSFS END IF(@KMLX='物理')BEGIN SELECT @WL=@KSFS END IF(@KMLX='化学')BEGIN SELECT @HX=@KSFS END IF(@KMLX='生物')BEGIN SELECT @SW=@KSFS END FETCH NEXT FROM SOC_CURSOR INTO @KMLX,@KSFS,@IDD END SELECT @ZF =0 SELECT @ZF=@YW+@SX+@YY+@WL+@HX+@SW INSERT INTO #STUSCORE VALUES (@IDD,@HX,@SW,@SX,@WL,@YY,@YW,@ZF) CLOSE SOC_CURSOR DEALLOCATE SOC_CURSOR FETCH NEXT FROM STC_CURSOR INTO @StudId END CLOSE STC_CURSOR DEALLOCATE STC_CURSOR ----------------------------------- DELETE FROM #STUSCORE WHERE 1=1 SELECT * FROM #STUSCORE SELECT A.ID,B.StuName AS 姓名 ,A.YW AS 语文,A.SX AS 数学,A.YY AS 英语,A.WL AS 物理,A.HX AS 化学,A.SW AS 生物,A.ZF AS 总分 FROM #STUSCORE A JOIN StuTable B ON A.ID =B.ID ORDER BY A.ZF DESC SELECT * FROM ScoreTable ----------------------------------- DECLARE STUCUR Insensitive SCROLL CURSOR FOR SELECT ID FROM StuTable DECLARE @AID INT OPEN STUCUR FETCH NEXT FROM STUCUR INTO @AID DELETE FROM StuTable WHERE ID=@AID FETCH FIRST FROM STUCUR INTO @AID PRINT @AID CLOSE STUCUR DEALLOCATE STUCUR SELECT * FROM StuTable ----------------------------------- DECLARE SSTUCUR CURSOR SCROLL FOR SELECT StuName FROM StuTable DECLARE @StuNam NVARCHAR(10) OPEN SSTUCUR FETCH ABSOLUTE 1 3 FROM SSTUCUR INTO @StuNam PRINT @StuNam CLOSE SSTUCUR DEALLOCATE SSTUCUR SELECT * FROM StuTable ------------------------------------ DECLARE SSTUCUR1 CURSOR FOR SELECT StuName FROM StuTable FOR UPDATE OF StuName OPEN SSTUCUR1 FETCH NEXT FROM SSTUCUR1 UPDATE StuTable SET StuName='褚强强' WHERE CURRENT OF SSTUCUR1 CLOSE SSTUCUR1 DEALLOCATE SSTUCUR1 DECLARE @PRI nvarchar(10) FETCH NEXT FROM SSTUCUR1 INTO @PRI --=========================================================== DECLARE @STUDENT NVARCHAR(20) SELECT TOP 200 @STUDENT=StuName FROM StuTable --WHERE PRINT @STUDENT --=========================全局变量================================= SELECT @@IDENTITY SELECT * INTO TABLE1 FROM StuTable select @@datefirst as '星期的第一天', datepart(dw, getDate()) AS '今天是星期'; select @@datefirst as '星期的第一天', datepart(MM, getDate()) AS '月份'; select @@dbts;--返回当前数据库唯一时间戳 --===========================逻辑控制语句============================= IF 0>0 SELECT '90' ELSE IF 1=2 SELECT '120' ELSE SELECT '110' ---------------------------------- PRINT '等三秒。。。。' waitfor delay '00:00:10';--定时三秒后执行 SELECT * FROM StuTable ---------------------------------- declare @i int; set @i = 1; while (@i < 11) begin if (@i < 5) begin set @i = @i + 1; continue; end print @i; set @i = @i + 1; end ---------------------------------- ----按分数划分等级A B C D SELECT *, '等级'=CASE WHEN SCORE >= 90 THEN 'A' WHEN 75<SCORE AND Score < 90 THEN 'B' WHEN 60<=Score AND Score<= 75 THEN 'C' WHEN SCORE<60 THEN 'D' END FROM ScoreTable ---------------------------------- --===================常量、变量================================================== DECLARE @CONSTANT NVARCHAR(10) SET @CONSTANT=N'120'--ASCII字符常量 SELECT @CONSTANT SET @CONSTANT ='120'--UNICODE字符常量 SELECT @CONSTANT SET @CONSTANT ='123.''' SELECT @CONSTANT ---------------------------------- DECLARE @CONST NVARCHAR(10) DECLARE @INT INT DECLARE @DATE DateTime SELECT @CONST,@INT,@DATE--常量、变量的默认值为null --用户不能建立全局变量,也不能用SET语句改变全局变量的值。 -----------全局变量--------------- SELECT @@VERSION AS 'SQL SERVER 版本', @@LANGUAGE AS '当前使用语言', @@MAX_CONNECTIONS AS '同时连接最大数目', @@ROWCOUNT AS '受上个sql命令影响的行数', @@SERVERNAME AS '服务器名称', @@TIMETICKS AS '当前计算机上每刻度的微秒数', @@TRANCOUNT AS '当前连接打开的事务数' ---------------------------------- SELECT MAX(StuAge) FROM StuTable Group By StuAge SELECT StuAge FROM StuTable Group By StuAge --=============================日期函数================================================= -------------------------------- DECLARE @TESTDATE DateTime SET @TESTDATE ='2013.1.1' SELECT DATEADD (DY,100,@TESTDATE),DATEADD(DD,100,@TESTDATE) --------------------------------- DECLARE @DATEDIFF1 DateTime DECLARE @DATEDIFF2 DateTime SET @DATEDIFF1 ='2013.03.10 10:23:23:23' SET @DATEDIFF2 ='2014.03.12 10:23:23:23' SELECT DATEDIFF(DD,@DATEDIFF1 ,@DATEDIFF2) --------------------------------- DECLARE @DATENAME DateTime SET @DATENAME ='2013.05.06 23:10:10' SELECT DATENAME(YY,@DATENAME) AS 年,DATENAME(MM,@DATENAME) AS 月,DATENAME(DD,@DATENAME) AS 天, DATENAME(WK,@DATENAME) AS 周,DATENAME(HH,@DATENAME) AS 时,DATENAME(MI ,@DATENAME) AS 分 --------------------------------- SELECT GETUTCDATE()--世界标准时间 --===============================字符函数================================================ DECLARE @SringTest char(10) SET @SringTest =ASCII('322') SELECT @SringTest DECLARE @Sring nvarchar(10) SET @Sring =ASCII('123') SELECT @Sring SELECT CHAR(50) SELECT LEFT('ASDFGE',4) SELECT RIGHT('QWEERYU',2) SELECT LTRIM(' 21455.') --SELECT 'A'+23 SELECT 'A'+LTRIM(STR(23)) SELECT 'A'+'23' SELECT LEN(STR(100)),LEN(LTRIM(STR(100))) SELECT StuName,ISNULL(StuAge,0) FROM StuTable WHERE StuAge is null SELECT StuName,ISNULL(StuAge,0) FROM StuTable WHERE ISNULL(StuAge,0)=0 SELECT StuName FROM StuTable WHERE ISNULL(StuAge,0)=0 SELECT REPLACE('231231200','2','X') SELECT REPLICATE('2',9) SELECT REVERSE('abcdefg') --================================运算符=============================================== SELECT ~14,23%12 SELECT * FROM StuTable WHERE StuAge !>30 SELECT * FROM StuTable WHERE StuAge <=30 SELECT * FROM StuTable WHERE 30<StuAge SELECT ID,StuAge,StuAge & ID FROM StuTable --位运算 DECLARE @J INT SELECT @J=8 WHILE(@J<18) BEGIN WHILE(@J<11) BEGIN IF @J=8 BEGIN CONTINUE END PRINT 'AB' SELECT @J=@J +1 END PRINT 'SD' SELECT @J=@J +1 END SELECT * FROM ClassTable --WAITFOR TIME '13:39:50' SELECT * FROM StuTable --==================================自定义函数========================================= ---------------------------标量型函数 --USE WSS_Content --GO --ALTER FUNCTION MYCOUNTER(@A INT,@B INT,@COUNTYPE NVARCHAR(3)) --RETURNS INT --AS --BEGIN -- DECLARE @RESULT INT -- SET @RESULT=CASE WHEN @COUNTYPE='+' THEN @A+@B -- WHEN @COUNTYPE='-' THEN @A-@B -- WHEN @COUNTYPE='*' THEN @A*@B -- WHEN @COUNTYPE='/' THEN @A/@B -- END -- return (@RESULT) --END SELECT dbo.MYCOUNTER(1,2,'+'),dbo.MYCOUNTER(1,2,'*'),dbo.MYCOUNTER(1000,4,'/') ---------------------------内嵌表值函数 --USE WSS_Content --GO --CREATE FUNCTION MYTABLEFUNC(@WHERE NVARCHAR(10)) --RETURNS TABLE --AS --RETURN (SELECT * FROM StuTable WHER --------------------------多语句表值函数 --===================================方法============================================== --E StuName=@Where) SELECT * FROM StuTable SELECT stuName from MYTABLEFUNC('徐俊强') --=====================================游标============================================= DECLARE STUCURR CURSOR FOR SELECT StuName FROM StuTable DECLARE @NAM nvarchar(10) OPEN STUCURR FETCH NEXT FROM STUCURR INTO @NAM WHILE(@@FETCH_STATUS=0) BEGIN PRINT @NAM FETCH NEXT FROM STUCURR INTO @NAM END CLOSE STUCURR DEALLOCATE STUCURR --=====================================事物========================================= BEGIN TRANSACTION TRANS GO UPDATE StuTable SET StuName='贾政09' WHERE ID='18' GO SAVE TRANSACTION CHANGE UPDATE StuTable SET StuName='李琦09' WHERE ID='19' GO ROLLBACK TRANSACTION TRANS PRINT 'PROGRAM GO ON' --COMMIT TRANSACTION SELECT * FROM StuTable --=============================存储过程============================================== ---------------系统存储过程---------------- exec sp_databases; --查看数据库 exec sp_tables; --查看表 exec sp_columns student;--查看列 exec sp_helpIndex student;--查看索引 exec sp_helpConstraint student;--约束 exec sp_stored_procedures; exec sp_helptext 'sp_stored_procedures';--查看存储过程创建、定义语句 exec sp_rename student, stuInfo;--修改表、索引、列的名称 exec sp_renamedb myTempDB, myDB;--更改数据库名称 exec sp_defaultdb 'master', 'myDB';--更改登录名的默认数据库 exec sp_helpdb;--数据库帮助,查询数据库信息 exec sp_helpdb master; ----------------自定义存储过程-------------------------- IF(EXISTS(SELECT * FROM sys.objects WHERE name='proc_getStuTable')) DROP PROC proc_getStuTable GO CREATE PROC proc_getStuTable AS SELECT * FROM StuTable EXEC proc_getStuTable ----------------带参数存储过程-------------------------- IF(OBJECT_ID('PROC_STU','P') IS NOT NULL) DROP PROC PROC_STU GO CREATE PROC PROC_STU(@StuName nvarchar(20)) AS SELECT * FROM StuTable WHERE (@StuName='' OR StuName=@StuName ) GO EXEC PROC_STU '赵春玉' SELECT * FROM StuTable ----------------带通配符参数存储过程------------------- IF(OBJECT_ID('PROC_STU1','P') IS NOT NULL) DROP PROC PROC_STU1 GO CREATE PROC PROC_STU1(@LikeName nvarchar(10)) AS SELECT * FROM StuTable WHERE StuName LIKE @LikeName GO EXEC PROC_STU1 '%春' ----------------带输出参数存储过程--------------------- IF(OBJECT_ID('PROC_STU2','P')) IS NOT NULL DROP PROC PROC_STU2 GO CREATE PROC PROC_STU2(@id nvarchar(10),@StuName nvarchar(20) output,@StuAge nvarchar(20) out) with encryption AS SELECT @StuName=StuName,@StuAge =StuAge FROM StuTable WHERE (@id='' OR ID=@id) AND (@StuName ='' OR StuName=@StuName) DECLARE @STU_NAME NVARCHAR(20) DECLARE @STU_AGE INT SET @STU_NAME ='赵春玉' EXEC PROC_STU2 ' ',@STU_NAME OUTPUT,@STU_AGE OUT PRINT @STU_NAME PRINT @STU_AGE SELECT * FROM StuTable WHERE StuName='赵春玉' exec sp_helptext 'PROC_STU2'; exec sp_helptext 'proc_temp_encryption'; --SELECT * FROM dbo.utTable26 WHERE DB0836A='2013/07/24' --INSERT INTO dbo.utTable26 (DB0836A) VALUES ('2013/07/24') -------------------------带游标参数的存储过程----------------------- if(OBJECT_ID('PROC_CURSOR','P') IS NOT NULL) DROP PROC PROC_CURSOR GO CREATE PROC PROC_CURSOR @CUR CURSOR VARYING OUTPUT AS SET @CUR=CURSOR FORWARD_ONLY STATIC FOR SELECT ID,StuName,StuAge FROM StuTable OPEN @CUR DECLARE @CURS CURSOR DECLARE @ID INT, @StuName nvarchar(20), @StuAge nvarchar(20) EXEC PROC_CURSOR @CUR=@CURS OUTPUT FETCH NEXT FROM @CURS INTO @ID,@StuName,@StuAge WHILE(@@FETCH_STATUS =0) BEGIN PRINT CAST(@ID AS NVARCHAR(10))+' '+@StuName+' '+@StuAge FETCH NEXT FROM @CURS INTO @ID,@StuName,@StuAge END GO ---------------分页存储过程------------------------ CREATE PROC PROC_PA(@StartIndex int,@EndIndex int) AS SELECT * FROM( SELECT *,ROW_NUMBER() OVER(ORDER BY ID) AS DID FROM StuTable ) T WHERE T.DID BETWEEN @StartIndex AND @EndIndex GO ALTER PROC PROC_PAGE(@pageIndex int,@pageSize int) AS DECLARE @StartIndex INT, @EndIndex INT SET @StartIndex = (@pageIndex-1)*@pageSize +1 SET @EndIndex =@StartIndex +@pageSize -1; EXEC PROC_PA @StartIndex,@EndIndex GO EXEC PROC_PAGE 1,20 EXEC PROC_PAGE 2,20 EXEC PROC_PAGE 3,20 GO --===================================触发器======================================== CREATE TRIGGER TRIG_StuTable ON StuTable FOR INSERT AS DECLARE @MAXID NVARCHAR(12) SELECT @MAXID=MAX(ID) FROM StuTable SELECT * FROM StuTable WHERE ID=@MAXID--向表StuTable中添加数据时,将新添的数据显示出来。 GO ---------------------------------------------- CREATE PROC InsertStuTableInfo(@stuName nvarchar(20),@stuAge int,@classId int) AS DECLARE @maxId int SELECT @maxId=MAX(ID) FROM StuTable INSERT INTO StuTable VALUES(@maxId+1,@stuName,@stuAge,@classId) GO ---------------------------------------------- EXEC InsertStuTableInfo '高工01',25,8 GO --============================================视图================================== CREATE VIEW View_StuTable AS SELECT * FROM StuTable GO DELETE FROM View_StuTable WHERE ID='18' DELETE FROM StuTable WHERE ID='18' GO CREATE VIEW View_Score AS SELECT * FROM ScoreTable GO DELETE FROM View_Score WHERE ID=2 UPDATE View_Score Set Score=90 WHERE ID=3 GO ALTER VIEW View_StuClass AS SELECT S.ID,S.ClassId,S.StuName,S.StuAge ,C.ClassName FROM StuTable S JOIN ClassTable C ON S.ClassId =C.ID GO /* 消息 4405,级别 16,状态 1,第 1 行 视图或函数 'View_StuClass' 不可更新,因为修改会影响多个基表。 附件:http://dl.vmall.com/c004cxnrfa http://dl.vmall.com/c03ulland3