SQL Server中Rowcount与@@Rowcount的用法

合集下载

SQLServer全局变量

SQLServer全局变量

SQLServer全局变量@@SERVERNAME : 返回运⾏SQL Server 2000本地服务器的名称。

1. @@REMSERVER : 返回登录记录中记载的远程SQL Server服务器的名称。

2. @@CONNECTIONS : 返回⾃上次启动SQL Server以来连接或试图连接的次数,⽤其可让管理⼈员⽅便地了解今天所有试图连接服务器的次数。

3. @@CURSOR_ROWS : 返回最后连接上并打开的游标中当前存在的合格⾏的数量。

4. @@ERROR : 返回最后执⾏的Transact-SQL语句的错误代码。

5. @@ROWCOUNT : 返回受上⼀语句影响的⾏数,任何不返回⾏的语句将这⼀变量设置为0。

6. @@VERSION : 返回SQL Server当前安装的⽇期、版本和处理器类型。

7. @@CPU_BUSY : 返回⾃SQL Server最近⼀次启动以来CPU的⼯作时间其单位为毫秒。

8. @@DATEFIRST : 返回使⽤SET DATEFIRST命令⽽被赋值的DATAFIRST参数值。

SET DATEFIRST命令⽤来指定每周的第⼀天是星期⼏。

9. @@DBTS : 返回当前数据库的时间戳值必须保证数据库中时间戳的值是惟⼀的。

10. @@FETCH_STATUS : 返回上⼀次FETCH语句的状态值。

11. @@IDENTITY : 返回最后插⼊⾏的标识列的列值。

12. @@IDLE : 返回⾃SQL Server最近⼀次启动以来CPU处于空闭状态的时间长短,单位为毫秒。

13. @@IO_BUSY : 返回⾃SQL Server最后⼀次启动以来CPU执⾏输⼊输出操作所花费的时间(毫秒)。

14. @@LANGID : 返回当前所使⽤的语⾔ID值。

15. @@LANGUAGE : 返回当前使⽤的语⾔名称。

16. @@LOCK_TIMEOUT: 返回当前会话等待锁的时间长短其单位为毫秒。

rowcount用法

rowcount用法

rowcount用法在不同的场景下,"rowcount"可以引用数据库查询的结果中所包含的行数。

在以下几个方面,可以详细介绍"rowcount"的使用方法和一些注意事项。

1.数据库连接在使用"rowcount"之前,首先需要建立与数据库的连接。

通常使用各种数据库连接库来实现,如Python中的"pymysql"、"psycopg2"、"sqlite3"等。

在连接数据库之后,可以执行SQL查询并通过"rowcount"获取结果集的行数。

```pythonimport pymysql#建立与MySQL数据库的连接connection = pymysql.connect(host='localhost',user='user',password='pass',db='database')#创建游标对象cursor = connection.cursor#执行SQL查询cursor.execute("SELECT * FROM table_name")#获取结果集的行数row_count = cursor.rowcountprint("行数:", row_count)#关闭游标和连接cursor.closeconnection.close```2.查询结果的行数"rowcount"属性返回的是最近一次执行SQL查询影响的行数。

在执行查询前,"rowcount"的值为-1,执行查询后,可以获取查询结果的行数。

```pythoncursor.execute("DELETE FROM table_name WHERE condition")row_count = cursor.rowcountprint("删除的行数:", row_count)cursor.execute("UPDATE table_name SET column_name=value WHERE condition")row_count = cursor.rowcountprint("更新的行数:", row_count)```3.注意事项- 不同的数据库连接库对"rowcount"属性的支持有所不同。

SQL Server 的基础知识

SQL Server 的基础知识

SQL Server 的基础知识一、数据类型字符型数据char[(n)]:存在固定长度的n个字符数据varchar[(n)]:存放可变长度的n个字符数据text:存放最大长度为2^31-1的字符数据Unicode数据Nchar[(n)]:存放固定长度的n个UNICODE数据Nvarchar[(n)]:存放可变长度的n个UNICODE数据NTEXT日期和时间数据datetime:存放入1753/1/1到9999/12/31的时间数据smalldatetime:存放从1900/1/1到2079/6/6的时间数字型数据bigint:存放从-2^63到2^63的整型数据int:存放人-2^31到2^63的整型数据smallint:存放从-2^15到2^15的整型数据tinyint:存放2从0到255的整型数据decimal[p[,s]]]、numeric[(p[,s])]:固定精度的小数据,当取最大精度时范围从-10^38-1到10^38-1float[(n)]:存放的浮点数real:存放浮点数货币数据money:smallmoney:二、建表CREATE TABLE语句例:create talbe customers(customerid intidentity(1,1)primary key,fristName varchar(20) not null,lastName varchar(20) not null,Address varchar(100),City varchar(20),Tel varchar(20) UNIQUE,Company varchar(50),Birthday datetime,Type tinyint default 1)Ceate table goods(Name varchar(20) constraint pk_goodsname primary key,Description varchar(200),Storage int,Supplier tinyint default(0),Price money)Create table orders(Ordered int identity(1,1) constraint pk_ordered primary key,Goodsname varchar(20) not nullForeignkey(customerid) references customers(customerid) on delete on action,Quantity int null constraint ck_quantity check(quantity>0),Ordersum money not null,Orderdate datetime default(getdate()))三、添加和删除列use marketalter table customers add emailaddress varchar(50) nullxonstraint ck_ea check(emailaddress like‟%@%‟)use marketalter table customers drop column emailaddress四、查询语句select …客户序号‟,customerid,firstname,lastname from customers在select _list中,可以使用算术运算符操纵列,对查询的结果进行计算,这种计算可以是针对多个列的。

SqlServer存储过程调用存储过程接收输出参数返回值

SqlServer存储过程调用存储过程接收输出参数返回值
接收输出参数:
DECLARE @count INT EXECUTE GetCustomers @count OUTPUT PRINT @count
2,带返回值
创建存储过பைடு நூலகம்:
ALTER PROCEDURE [dbo].[GetCustomers] AS
SELECT [CustomerID] ,[CompanyName] ,[ContactName] ,[ContactTitle] ,[Address] ,[City] ,[Region] ,[PostalCode] ,[Country] ,[Phone] ,[Fax] FROM [Northwind].[dbo].[Customers] RETURN @@rowcount
创建存储过程:
ALTER PROCEDURE [dbo].[GetCustomers] (@rowcount INT OUTPUT) AS
SELECT [CustomerID] ,[CompanyName] ,[ContactName] ,[ContactTitle] ,[Address] ,[City] ,[Region] ,[PostalCode] ,[Country] ,[Phone] ,[Fax] FROM [Northwind].[dbo].[Customers] SET @rowcount=@@rowcount
接收返回值:
DECLARE @count INT EXECUTE @count=GetCustomers PRINT @count
以上所述是小编给大家介绍的Sql Server 存储过程调用存储过程接收输出参数返回值,希望对大家有所帮助,如果大家有任何 疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

sqlserver调用存储过程语句

sqlserver调用存储过程语句

sqlserver调用存储过程语句SQL Server是一种关系型数据库管理系统,它支持存储过程的调用。

存储过程是一组预定义的SQL语句,可以在数据库中存储和重复使用。

在SQL Server中,调用存储过程可以提高数据库的性能和安全性。

下面是SQL Server调用存储过程的语句。

1. 创建存储过程在SQL Server中,可以使用CREATE PROCEDURE语句创建存储过程。

例如,下面的语句创建了一个名为GetEmployee的存储过程,该存储过程返回Employee表中指定员工的信息。

CREATE PROCEDURE GetEmployee@EmployeeID intASSELECT * FROM Employee WHERE EmployeeID = @EmployeeID2. 调用存储过程在SQL Server中,可以使用EXECUTE语句或EXEC语句调用存储过程。

例如,下面的语句调用了GetEmployee存储过程,并传递了EXECUTE GetEmployee 1或者EXEC GetEmployee 13. 传递参数在调用存储过程时,可以传递参数。

在存储过程中,可以使用@符号定义参数。

例如,下面的语句创建了一个名为GetEmployeeByDepartment的存储过程,该存储过程返回指定部门的所有员工信息。

CREATE PROCEDURE GetEmployeeByDepartment@DepartmentID intASSELECT * FROM Employee WHERE DepartmentID =@DepartmentID在调用存储过程时,可以传递DepartmentID参数的值。

例如,下面的语句调用了GetEmployeeByDepartment存储过程,并传递了EXECUTE GetEmployeeByDepartment 2或者EXEC GetEmployeeByDepartment @DepartmentID = 24. 返回值在存储过程中,可以使用RETURN语句返回一个整数值。

sqlserver 打印语句

sqlserver 打印语句

sqlserver 打印语句在SQL Server中,使用PRINT语句可以在查询执行时打印消息或变量的值。

这对于调试和跟踪程序非常有用。

PRINT语句的基本语法如下:sql.PRINT 'Your message or variable value';例如,如果要打印一个简单的消息,可以这样做:sql.PRINT 'Hello, this is a message';如果要打印变量的值,可以这样做:sql.DECLARE @myVariable INT;SET @myVariable = 10;PRINT 'The value of myVariable is: ' + CAST(@myVariable AS VARCHAR);在上面的例子中,我们声明了一个整型变量@myVariable,并将其设置为10。

然后使用PRINT语句打印变量的值。

另外,PRINT语句也可以与查询一起使用,以便在执行查询时打印消息或变量的值。

例如:sql.DECLARE @rowCount INT;SELECT @rowCount = COUNT() FROM yourTable;PRINT 'The total number of rows in yourTable is: ' + CAST(@rowCount AS VARCHAR);这将在执行查询时打印表中行的总数。

需要注意的是,PRINT语句在存储过程、触发器或批处理中也可以使用,以便在执行过程中输出消息或变量的值。

总之,PRINT语句在SQL Server中是一个非常有用的调试工具,可以帮助开发人员跟踪程序执行过程中的变量值或输出消息。

SQLSERVER中统计所有表的记录数

SQLSERVER中统计所有表的记录数今天群⾥的⼀个朋友问了个问题:如何把数据库⾥所有表的记录数都统计出来?由于以前我曾经试着写过⼀个存储过程,作⽤就是删除所有表的内容,思路是这样的:⾸先通过sysobjects表构造⼀个sql语句字符串'DELETE 表名',其中表名就是sysobjects中的name列,把这些DELETE语句字符串连接起来的⽅法⼀是通过游标,⼆则是直接利⽤如下语句:select @sql = @sql + 'DELETE ' + name from sysobjects where xtype='U';这是⼀个很有⽤的技巧,在合适的地⽅⽤会很⼤程度的优化语句运⾏速度.然后就是通过exec(@sql)执⾏该字符串.⽽把数据库所有表的记录数统计出来和这个思路⼏乎完全⼀样,不同的就是把'DELETE 表名' 改为'SELECT 表名,COUNT(1) FROM 表名',主要这点不同⽽已,如果构造完字符串并执⾏完毕,可以把结果输出到⼀个临时表,那么再统计所有记录数就轻⽽易举了.下⾯就是我写的⼀个语句:declare @sql varchar(8000),@count int,@step intset nocount on--@step越⼤运⾏速度越快,但如果太⼤会造成⽣成的sql字符串超出限制导致语句不完整出错--建议为50set @step = 50if object_id(N'tempdb.db.#temp') is not nulldrop table #tempcreate table #temp (name sysname,count numeric(18))if object_id(N'tempdb.db.#temp1') is not nulldrop table #temp1create table #temp1 (id int identity(1,1),name sysname)insert into #temp1(name)select name from sysobjects where xtype = 'u';set @count = @@rowcount while @count>0beginset @sql = ''select @sql = @sql + ' select ''' + name + ''',count(1) from ' + name + ' union'from #temp1 where id > @count - @step and id <= @countset @sql = left(@sql,len(@sql) - len('union'))insert into #temp exec (@sql)set @count = @count - @stependselect count(count) 总表数,sum(count) 总记录数 from #tempselect * from #temp order by count,nameset nocount off经过测试,该⽅法可以通过,不过有时候@step的值需要⼿动设置⼀下,@step=50应该就可以满⾜⼤部分数据库的需要了.如果表名都⽐较短的话,可以设置@step=80或者100.后来我⼜去上⽹搜索其他统计数据库所有表记录数的语句,发现了下⾯的⽅法:create table #(id int identity ,tblname varchar(50),num int)declare @name varchar(30)declare roy cursor for select name from sysobjects where xtype='U'open royfetch next from roy into @namewhile @@fetch_status=0begindeclare @i intdeclare @sql nvarchar(1000)set @sql='select @n=count(1) from '+@nameexec sp_executesql @sql,N'@n int output',@i outputinsert into # select @name,@Ifetch next from roy into @nameendclose roydeallocate royselect * from #该⽅法⽤到了游标,如果数据库表很多的话速度可能会⽐较慢,但是该表不受表名长短影响,对所有数据库都适⽤.第三种⽅法,利⽤系统的对象表和索引表:set nocount onif object_id(N'tempdb.db.#temp') is not nulldrop table #tempcreate table #temp (name sysname,count numeric(18))insert into #tempselect ,i.rowsfrom sysobjects o,sysindexes iwhere o.id=i.id and o.Xtype='U' and i.indid<2select count(count) 总表数,sum(count) 总记录数 from #tempselect * from #tempset nocount off该⽅法执⾏速度绝对最快,但是结果好象并不是太准确,稍微有⼀些偏差.所以如果对数据量⽐较⼤⽽且对统计结果要求⽐较低的,该⽅法绝对是第⼀选择.如果要求统计绝对准确的记录数⽽且表的数量⽐较多的话,个⼈感觉第⼀个⽅法应该是个不错的选择.第三个⽅法主要是利⽤了系统索引表sysindexes中索引ID indid<1的⾏中的rows列存有该表的⾏数这⼀特点.最后⼀种⽅法是利⽤隐藏未公开的系统存储过程sp_MSforeachtableCREATE TABLE #temp (TableName VARCHAR (255), RowCnt INT)EXEC sp_MSforeachtable 'INSERT INTO #temp SELECT ''?'', COUNT(*) FROM ?'SELECT TableName, RowCnt FROM #temp ORDER BY TableNameDROP TABLE #temp。

sqlserver中局部变量与全局变量的申明与赋值(转)

sqlserver中局部变量与全局变量的申明与赋值(转)局部变量⽤⼀个@标识,全局变量⽤两个@(常⽤的全局变量⼀般都是已经定义好的);申明局部变量语法:declare @变量名数据类型;例如:declare @num int;赋值:有两种⽅法式(@num为变量名,value为值)set @num=value; 或 select @num=value;如果想获取查询语句中的⼀个字段值可以⽤select给变量赋值,如下:select @num=字段名 from 表名 where ……中变量不⽤事前申明,在⽤的时候直接⽤“@变量名”使⽤就可以了。

第⼀种⽤法:set @num=1; 或set @num:=1; //这⾥要使⽤变量来保存数据,直接使⽤@num变量第⼆种⽤法:select @num:=1; 或 select @num:=字段名 from 表名 where ……注意上⾯两种赋值符号,使⽤set时可以⽤“=”或“:=”,但是使⽤select时必须⽤“:=赋值”在sql中,我们常常使⽤临时表来存储临时结果,对于结果是⼀个集合的情况,这种⽅法⾮常实⽤,但当结果仅仅是⼀个数据或者是⼏个数据时,还要去建⼀个表,显得就⽐较⿇烦,另外,当⼀个sql语句中的某些元素经常变化时,⽐如选择条件,(⾄少我想)应该使⽤局部变量。

当然ms sql server的全局变量也很有⽤。

> > > > 局部变量声明:declare @local_variable data_type@local_variable 是变量的名称。

变量名必须以 at 符 (@) 开头。

data_type 是任何由系统提供的或⽤户定义的数据类型。

变量不能是text、ntext 或 image 数据类型。

⽰例:use masterdeclare @sel_type char(2)declare @sel_cunt numeric(10)set @sel_type = 'u '/*user table*/set @sel_cunt = 10/*返回系统中⽤户表的数⽬*/select @sel_cunt = count(*)from sysobjectswhere type = @sel_typeselect @sel_cunt as 'user table ' 's count '如果要返回系统表的数⽬,可以⽤set @sel_type = 's '可能这个例⼦并不能说明使⽤变量的好处,我只是想说明使⽤⽅法。

sqlserver删除重复数据保留最大id的SQL语句

sqlserver删除重复数据保留最⼤id的SQL语句SqlServer 删除重复数据保留最⼤id的SQL语句多种⽅法:1--1、⽤于查询重复处理记录(如果列没有⼤⼩关系时2000⽤⽣成⾃增列和临时表处理,SQL2005⽤row_number函数处理)23--II、Name相同ID最⼤的记录,与min相反:4⽅法1:5Select*from #T a where not exists(select1from #T where Name= and ID>a.ID)67⽅法2:8select a.*from #T a join (select max(ID)ID,Name from #T group by Name) b on = and a.ID=b.ID order by ID910⽅法3:11select*from #T a where ID=(select max(ID) from #T where Name=) order by ID1213⽅法4:14select a.*from #T a join #T b on = and a.ID<=b.ID group by a.ID,,a.Memo having count(1)=11516⽅法5:17select*from #T a group by ID,Name,Memo having ID=(select max(ID)from #T where Name=)1819⽅法6:20select*from #T a where (select count(1) from #T where Name= and ID>a.ID)=02122⽅法7:23select*from #T a where ID=(select top1 ID from #T where Name= order by ID desc)2425⽅法8:26select*from #T a where ID!<all(select ID from #T where Name=)2728⽅法9(注:ID为唯⼀时可⽤):29select*from #T a where ID in(select max(ID) from #T group by Name)3031--SQL2005:3233⽅法10:34select ID,Name,Memo from (select*,max(ID)over(partition by Name) as MinID from #T a)T where ID=MinID3536⽅法11:37select ID,Name,Memo from (select*,row_number()over(partition by Name order by ID desc) as MinID from #T a)T where MinID=13839⽣成结果2:40/*41ID Name Memo42----------- ---- ----433 A A3445 B B24546(2 ⾏受影响)47*/484950--2、删除重复记录有⼤⼩关系时,保留⼤的其中⼀个记录51--II、Name相同ID保留最⼤的⼀条记录:5253⽅法1:54delete a from #T a where exists(select1from #T where Name= and ID>a.ID)5556⽅法2:57delete a from #T a left join (select max(ID)ID,Name from #T group by Name) b on = and a.ID=b.ID where b.Id is null5859⽅法3:60delete a from #T a where ID not in (select max(ID) from #T where Name=)6162⽅法4(注:ID为唯⼀时可⽤):63delete a from #T a where ID not in(select max(ID)from #T group by Name)6465⽅法5:66delete a from #T a where (select count(1) from #T where Name= and ID>a.ID)>06768⽅法6:69delete a from #T a where ID<>(select top1 ID from #T where Name= order by ID desc)71⽅法7:72delete a from #T a where ID<any(select ID from #T where Name=)737475select*from #T76/*77ID Name Memo78----------- ---- ----793 A A3805 B B28182(2 ⾏受影响)83*/--处理表重复记录(查询和删除)/******************************************************************************************************************************************************1、Num、Name相同的重复值记录,没有⼤⼩关系只保留⼀条2、Name相同,ID有⼤⼩关系时,保留⼤或⼩其中⼀个记录整理⼈:中国风(Roy)⽇期:2008.06.06******************************************************************************************************************************************************/ --1、⽤于查询重复处理记录(如果列没有⼤⼩关系时2000⽤⽣成⾃增列和临时表处理,SQL2005⽤row_number函数处理)--> --> (Roy)⽣成測試數據if not object_id('Tempdb..#T') is nulldrop table #TGoCreate table #T([ID] int,[Name] nvarchar(1),[Memo] nvarchar(2))Insert #Tselect 1,N'A',N'A1' union allselect 2,N'A',N'A2' union allselect 3,N'A',N'A3' union allselect 4,N'B',N'B1' union allselect 5,N'B',N'B2'Go--I、Name相同ID最⼩的记录(推荐⽤1,2,3),⽅法3在SQl05时,效率⾼于1、2⽅法1:Select * from #T a where not exists(select 1 from #T where Name= and ID<a.ID)⽅法2:select a.* from #T a join (select min(ID)ID,Name from #T group by Name) b on = and a.ID=b.ID⽅法3:select * from #T a where ID=(select min(ID) from #T where Name=)⽅法4:select a.* from #T a join #T b on = and a.ID>=b.ID group by a.ID,,a.Memo having count(1)=1⽅法5:select * from #T a group by ID,Name,Memo having ID=(select min(ID)from #T where Name=)⽅法6:select * from #T a where (select count(1) from #T where Name= and ID<a.ID)=0⽅法7:select * from #T a where ID=(select top 1 ID from #T where Name= order by ID)⽅法8:select * from #T a where ID!>all(select ID from #T where Name=)⽅法9(注:ID为唯⼀时可⽤):select * from #T a where ID in(select min(ID) from #T group by Name)--SQL2005:⽅法10:select ID,Name,Memo from (select *,min(ID)over(partition by Name) as MinID from #T a)T where ID=MinID⽅法11:select ID,Name,Memo from (select *,row_number()over(partition by Name order by ID) as MinID from #T a)T where MinID=1⽣成结果:ID Name Memo----------- ---- ----1 A A14 B B1(2 ⾏受影响)*/--2、删除重复记录有⼤⼩关系时,保留其中最⼩的⼀个记录--> --> (Roy)⽣成測試數據if not object_id('Tempdb..#T') is nulldrop table #TGoCreate table #T([ID] int,[Name] nvarchar(1),[Memo] nvarchar(2))Insert #Tselect 1,N'A',N'A1' union allselect 2,N'A',N'A2' union allselect 3,N'A',N'A3' union allselect 4,N'B',N'B1' union allselect 5,N'B',N'B2'Go--I、Name相同ID最⼩的记录(推荐⽤1,2,3),保留最⼩⼀条⽅法1:delete a from #T a where exists(select 1 from #T where Name= and ID<a.ID)⽅法2:delete a from #T a left join (select min(ID)ID,Name from #T group by Name) b on = and a.ID=b.ID where b.Id is null ⽅法3:delete a from #T a where ID not in (select min(ID) from #T where Name=)⽅法4(注:ID为唯⼀时可⽤):delete a from #T a where ID not in(select min(ID)from #T group by Name)⽅法5:delete a from #T a where (select count(1) from #T where Name= and ID<a.ID)>0⽅法6:delete a from #T a where ID<>(select top 1 ID from #T where Name= order by ID)⽅法7:delete a from #T a where ID>any(select ID from #T where Name=)select * from #T⽣成结果:/*ID Name Memo----------- ---- ----1 A A14 B B1(2 ⾏受影响)*/--3、删除重复记录没有⼤⼩关系时,处理重复值--> --> (Roy)⽣成測試數據if not object_id('Tempdb..#T') is nulldrop table #TGoCreate table #T([Num] int,[Name] nvarchar(1))Insert #Tselect 1,N'A' union allselect 1,N'A' union allselect 1,N'A' union allselect 2,N'B' union allselect 2,N'B'Go⽅法1:if object_id('Tempdb..#') is not nulldrop table #Select distinct * into # from #T--排除重复记录结果集⽣成临时表#truncate table #T--清空表insert #T select * from # --把临时表#插⼊到表#T中--查看结果select * from #T/*Num Name----------- ----1 A2 B(2 ⾏受影响)*/--重新执⾏测试数据后⽤⽅法2⽅法2:alter table #T add ID int identity--新增标识列godelete a from #T a where exists(select 1 from #T where Num=a.Num and Name= and ID>a.ID)--只保留⼀条记录goalter table #T drop column ID--删除标识列--查看结果select * from #T/*Num Name----------- ----1 A2 B(2 ⾏受影响)*/--重新执⾏测试数据后⽤⽅法3⽅法3:declare Roy_Cursor cursor local forselect count(1)-1,Num,Name from #T group by Num,Name having count(1)>1declare @con int,@Num int,@Name nvarchar(1)open Roy_Cursorfetch next from Roy_Cursor into @con,@Num,@Namewhile @@Fetch_status=0beginset rowcount @con;delete #T where Num=@Num and Name=@Nameset rowcount 0;fetch next from Roy_Cursor into @con,@Num,@Nameendclose Roy_Cursordeallocate Roy_Cursor--查看结果select * from #T/*Num Name----------- ----1 A2 B(2 ⾏受影响)*/---------------------完整代码(折叠)----------------------1--处理表重复记录(查询和删除)2/****************************************************************************************************************************************************** 31、Num、Name相同的重复值记录,没有⼤⼩关系只保留⼀条42、Name相同,ID有⼤⼩关系时,保留⼤或⼩其中⼀个记录5整理⼈:中国风(Roy)67⽇期:2008.06.068******************************************************************************************************************************************************/ 910--1、⽤于查询重复处理记录(如果列没有⼤⼩关系时2000⽤⽣成⾃增列和临时表处理,SQL2005⽤row_number函数处理)1112--> --> (Roy)⽣成測試數據1314if not object_id('Tempdb..#T') is null15drop table #T16Go17Create table #T([ID]int,[Name]nvarchar(1),[Memo]nvarchar(2))18Insert #T19select1,N'A',N'A1'union all20select2,N'A',N'A2'union all21select3,N'A',N'A3'union all22select4,N'B',N'B1'union all23select5,N'B',N'B2'24Go252627--I、Name相同ID最⼩的记录(推荐⽤1,2,3),⽅法3在SQl05时,效率⾼于1、228⽅法1:29Select*from #T a where not exists(select1from #T where Name= and ID<a.ID)3031⽅法2:32select a.*from #T a join (select min(ID)ID,Name from #T group by Name) b on = and a.ID=b.ID3334⽅法3:35select*from #T a where ID=(select min(ID) from #T where Name=)3637⽅法4:38select a.*from #T a join #T b on = and a.ID>=b.ID group by a.ID,,a.Memo having count(1)=13940⽅法5:41select*from #T a group by ID,Name,Memo having ID=(select min(ID)from #T where Name=)4243⽅法6:44select*from #T a where (select count(1) from #T where Name= and ID<a.ID)=04546⽅法7:47select*from #T a where ID=(select top1 ID from #T where Name= order by ID)4849⽅法8:50select*from #T a where ID!>all(select ID from #T where Name=)5152⽅法9(注:ID为唯⼀时可⽤):53select*from #T a where ID in(select min(ID) from #T group by Name)5455--SQL2005:5657⽅法10:58select ID,Name,Memo from (select*,min(ID)over(partition by Name) as MinID from #T a)T where ID=MinID5960⽅法11:6162select ID,Name,Memo from (select*,row_number()over(partition by Name order by ID) as MinID from #T a)T where MinID=1 6364⽣成结果:65/*66ID Name Memo67----------- ---- ----681 A A1694 B B17071(2 ⾏受影响)72*/737475--II、Name相同ID最⼤的记录,与min相反:76⽅法1:77Select*from #T a where not exists(select1from #T where Name= and ID>a.ID)7879⽅法2:80select a.*from #T a join (select max(ID)ID,Name from #T group by Name) b on = and a.ID=b.ID order by ID 8182⽅法3:83select*from #T a where ID=(select max(ID) from #T where Name=) order by ID8485⽅法4:86select a.*from #T a join #T b on = and a.ID<=b.ID group by a.ID,,a.Memo having count(1)=18788⽅法5:89select*from #T a group by ID,Name,Memo having ID=(select max(ID)from #T where Name=)9091⽅法6:92select*from #T a where (select count(1) from #T where Name= and ID>a.ID)=09394⽅法7:95select*from #T a where ID=(select top1 ID from #T where Name= order by ID desc)9697⽅法8:98select*from #T a where ID!<all(select ID from #T where Name=)99100⽅法9(注:ID为唯⼀时可⽤):101select*from #T a where ID in(select max(ID) from #T group by Name)102103--SQL2005:104105⽅法10:106select ID,Name,Memo from (select*,max(ID)over(partition by Name) as MinID from #T a)T where ID=MinID107108⽅法11:109select ID,Name,Memo from (select*,row_number()over(partition by Name order by ID desc) as MinID from #T a)T where MinID=1 110111⽣成结果2:112/*113ID Name Memo114----------- ---- ----1153 A A31165 B B2117118(2 ⾏受影响)119*/120121122123--2、删除重复记录有⼤⼩关系时,保留⼤或⼩其中⼀个记录124125126--> --> (Roy)⽣成測試數據127128if not object_id('Tempdb..#T') is null129drop table #T130Go131Create table #T([ID]int,[Name]nvarchar(1),[Memo]nvarchar(2))132Insert #T133select1,N'A',N'A1'union all134select2,N'A',N'A2'union all135select3,N'A',N'A3'union all136select4,N'B',N'B1'union all137select5,N'B',N'B2'138Go139140--I、Name相同ID最⼩的记录(推荐⽤1,2,3),保留最⼩⼀条141⽅法1:142delete a from #T a where exists(select1from #T where Name= and ID<a.ID)143144⽅法2:145delete a from #T a left join (select min(ID)ID,Name from #T group by Name) b on = and a.ID=b.ID where b.Id is null 146147⽅法3:148delete a from #T a where ID not in (select min(ID) from #T where Name=)149150⽅法4(注:ID为唯⼀时可⽤):151delete a from #T a where ID not in(select min(ID)from #T group by Name)152153⽅法5:154delete a from #T a where (select count(1) from #T where Name= and ID<a.ID)>0155156⽅法6:157delete a from #T a where ID<>(select top1 ID from #T where Name= order by ID)158159⽅法7:160delete a from #T a where ID>any(select ID from #T where Name=)161162163164select*from #T165166⽣成结果:167/*168ID Name Memo169----------- ---- ----1701 A A11714 B B1172173(2 ⾏受影响)174*/175176177--II、Name相同ID保留最⼤的⼀条记录:178179⽅法1:180delete a from #T a where exists(select1from #T where Name= and ID>a.ID)181182⽅法2:183delete a from #T a left join (select max(ID)ID,Name from #T group by Name) b on = and a.ID=b.ID where b.Id is null 184185⽅法3:186delete a from #T a where ID not in (select max(ID) from #T where Name=)187188⽅法4(注:ID为唯⼀时可⽤):189delete a from #T a where ID not in(select max(ID)from #T group by Name)190191⽅法5:192delete a from #T a where (select count(1) from #T where Name= and ID>a.ID)>0193194⽅法6:195delete a from #T a where ID<>(select top1 ID from #T where Name= order by ID desc)196197⽅法7:198delete a from #T a where ID<any(select ID from #T where Name=)199200201select*from #T202/*203ID Name Memo204----------- ---- ----2053 A A32065 B B2207208(2 ⾏受影响)209*/210211212213214215--3、删除重复记录没有⼤⼩关系时,处理重复值216217218--> --> (Roy)⽣成測試數據219220if not object_id('Tempdb..#T') is null221drop table #T222Go223Create table #T([Num]int,[Name]nvarchar(1))224Insert #T225select1,N'A'union all226select1,N'A'union all227select1,N'A'union all228select2,N'B'union all229select2,N'B'230Go231232⽅法1:233if object_id('Tempdb..#') is not null234drop table #235Select distinct*into # from #T--排除重复记录结果集⽣成临时表#236237truncate table #T--清空表238239insert #T select*from # --把临时表#插⼊到表#T中240241--查看结果242select*from #T243244/*245Num Name246----------- ----2471 A2482 B249250(2 ⾏受影响)251*/252253--重新执⾏测试数据后⽤⽅法2254⽅法2:255256alter table #T add ID int identity--新增标识列257go258delete a from #T a where exists(select1from #T where Num=a.Num and Name= and ID>a.ID)--只保留⼀条记录259go260alter table #T drop column ID--删除标识列261262--查看结果263select*from #T264265/*266Num Name267----------- ----2681 A2692 B270271(2 ⾏受影响)272273*/274275--重新执⾏测试数据后⽤⽅法3276⽅法3:277declare Roy_Cursor cursor local for278select count(1)-1,Num,Name from #T group by Num,Name having count(1)>1 279declare@con int,@Num int,@Name nvarchar(1)280open Roy_Cursor281fetch next from Roy_Cursor into@con,@Num,@Name282while@@Fetch_status=0283begin284set rowcount@con;285delete #T where Num=@Num and Name=@Name286set rowcount0;287fetch next from Roy_Cursor into@con,@Num,@Name288end289close Roy_Cursor290deallocate Roy_Cursor291292--查看结果293select*from #T294/*295Num Name296----------- ----2971 A2982 B299300(2 ⾏受影响)301*/删除重复数据保留最⼤id或最⼩id的SQL语句··。

SQLServer存储过程Return、output参数及使用技巧

SQLServer存储过程Return、output参数及使⽤技巧SQL Server⽬前正⽇益成为WindowNT操作系统上⾯最为重要的⼀种数据库管理系统,随着 SQL Server2000的推出,微软的这种数据库服务系统真正地实现了在WindowsNT/2000系列操作系统⼀统天下的局⾯,在微软的操作系统上,没有任何⼀种数据库系统能与之抗衡,包括数据库领域中的领头⽺甲⾻⽂公司的看家数据库Oracle在内。

不可否认,SQL Server最⼤的缺陷就是只能运⾏在微软⾃⼰的操作系统上,这⼀点是SQL Server的致命点。

但在另⼀⽅⾯却也成了最好的促进剂,促使SQL Server在⾃⼰仅有的“⼟地”上⾯将⾃⼰的功能发挥到了极⾄最⼤限度的利⽤了NT系列操作系统的各种潜能!作为SQL Server数据库系统中很重要的⼀个概念就是存储过程,合理的使⽤存储过程,可以有效的提⾼程序的性能;并且将商业逻辑封装在数据库系统中的存储过程中,可以⼤⼤提⾼整个软件系统的可维护性,当你的商业逻辑发⽣改变的时候,不再需要修改并编译客户端应⽤程序以及重新分发他们到为数众多的⽤户⼿中,你只需要修改位于服务器端的实现相应商业逻辑的存储过程即可。

合理的编写⾃⼰需要的存储过程,可以最⼤限度的利⽤SQL Server的各种资源。

下⾯我们来看看各种编写SQL Server 存储过程和使⽤存储过程的技巧经验。

Input 此参数只⽤于将信息从应⽤程序传输到存储过程。

InputOutput 此参数可将信息从应⽤程序传输到存储过程,并将信息从存储过程传输回应⽤程序。

Output 此参数只⽤于将信息从存储过程传输回应⽤程序。

ReturnValue 此参数表⽰存储过程的返回值。

SQL Server 的存储过程参数列表中不显⽰该参数。

它只与存储过程的 RETURN 语句中的值相关联。

存储过程为主键⽣成新值后,通常使⽤存储过程中的 RETURN 语句返回该值,因此⽤来访问该值的参数类型是 ReturnValue 参数。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

rowcount的用法:
rowcount的作用就是用来限定后面的sql在返回指定的行数之后便停止处理,比如下面的示例,
set rowcount 10
select * from 表A
这样的查询只会返回表A中的前10条数据。

它和 "select top 10 * from 表A" 的作用一样。

注意一点,set rowcount 的设置会在整个会话中有效。

比如下面的sql示例:set rowcount 10
select * from 表A
go
select * from 表B
表A和表B都只会返回前10条数据。

要取消set rowcount的限定,只要设置 set rowcount 0 就可以了。

从上面的示例来看,好像rowcount没有多大的用处,限制查询结果的数据,我们使用top就可以了,而且还不用担心如果忘记取消rowcount的设置而对后面的sql的影响。

但在下面的情况下,rowcount的设置就会给我们带来很大的方便哦。

我们都知道select top 后面不能加参数,只能使用一个具体的int类型的数字。

如果我们想实现top后面跟参数的功能,就只有构造sql字符串,然后使用exec来执行了。

比如:
declare @n int
declare @sql nvarchar(1000)
set @n=10
set @sql='select top '+cast(@n as varchar(10))+' * from 表A'
exec(@sql)
先不说上面语句中exec的性能,单从sql的可读性上来看就很不友好。

但如果我们使用rowcount来解决,就显的很优雅了,因为set rowcount后面是可以使用参数的。

示例如下:
declare @n int
set @n=10
set rowcount @n
select * from 表A
注意:set rowcount的限定对修改,删除一样有效。

比如下面的示例:
set rowcount 10
update 表a set qty=10 where id<100
这样,上面语句最多只会修改表a中id<100的前10条数据(假设id<100的数据数量大于10)
删除也是一样
set rowcount 10
delete from 表a
这样,上面的语句最多只会删除表a中前10条数据。

@@Rowcount的用法
@@Rowcount与Rowcount看起来很像,只相差了两个@,但它们的功能是不一样的,@@Rowcount主要是返回上次sql语句所影响的数据行数,比如:
select top 2 * from 表A
select @@Rowcount
如果表A中的数据量大于或等于2,那么select @@Rowcount就会返回2,如果只有1条或0条数据,那么select @@Rowcount就会返回1或者0。

注意,不要把@@Rowcount理解为只返回查询的结果数量,删除,修改,新增等语句,也会正确的返回@@Rowcount值。

比如:
update 表A set gid='a' where gid='a'
select @@Rowcount
如果表A中存在gid='a'的数据,那么select @@Rowcount就会返回它所修改数据的行数,如果不存在gid='a'的数据,那么select @@Rowcount就会返回0,删除与新增都是同样。

那么,哪些地方我们会用到@@Rowcount呢?
一、可能我们见到@@Rowcount身影最多的地方是触发器中,好的触发器,一般都会在最前面加上if @@rowcount=0 return语句,比如:
create trigger ti_tablea on tablea after update
as
if @@rowcount=0 return
……
这样,如果tablea被修改的数据行数为0,那么触发器ti_tablea就会直接退出,而不用执行后面的代码了。

二、第二个可能用到的地方就是我们可以使用@@rowcount来作递归或循环。

比如下面示例:
declare @n int
set @n=1
select * from client_goods where id=@n
while @@rowcount>0
begin
set @n=@n+1
select * from client_goods where id=@n
end
这个示例是先查询client_goods中是否有id=1的数据,如果有,再查询是否有id=2的数据,一直查下去,直到id没有连续为止。

当然大家在看这个示例的时候不要考虑这个示例的意义,它只是说明了@@rowcount可以作为循环条件来用。

rowcount与@@rowcount的其它用法,欢迎大家在评论中补充。

相关文档
最新文档