您的位置:

首页 >

5060官方网址大全 >

sql 游标的使用—游标FOR循环小例子 >

sql 游标的使用—游标FOR循环小例子

2016-05-07 03:18:22

分类:5060官方网址大全

例子: 显示emp表所有雇员名及其工资:复制代码 代码如下:declarecursor emp_cursor is select ename,sal from emp ;beginfor emp_record in emp_cursor loopdbms_output.put_line('姓名: '||emp_record.ename||' , 工资: '||emp_record.sal);end loop;end ;/anonymous block completed姓名: SMITH , 工资: 880姓名: ALLEN , 工资: 1600姓名: WARD , 工资: 1250姓名: JONES , 工资: 3272.5姓名: MARTIN , 工资: 1250姓名: BLAKE , 工资: 2850姓名: CLARK , 工资: 2450姓名: SCOTT , 工资: 2000姓名: KING , 工资: 5000姓名: TURNER , 工资: 1500姓名: ADAMS , 工资: 1210姓名: JAMES , 工资: 950姓名: FORD , 工资: 3300姓名: MILLER , 工资:

Microsoft included several hundred stored procedures in the various versions of Microsoft SQL Server and it has documented a good percentage of them. But many stored procedures remain undocumented. Some are used within the Enterprise Manager GUI in SQL 2000 and were not intended to be used by other processes. Microsoft has slated some of these stored procedures to be removed (or they have been removed) from future versions of SQL Server. While these stored procedures can be very useful and save you lots of time, they can be changed at any time in their function or they can simply be removed.The chart below shows that while many of the procedures have been carried through from one version of Microsoft SQL Server to another, new stored procedures have been introduced, and some have been removed from the install package. Most, if not all, of the procedures require the user to be a member of the sysadmin fixed server role in order to execute the procedures. The stored procedures that interact with the file system also require that the user executing the procedure (as well as SQL Server's service account) have access to the file/folder.Procedure NameSQL 2000SQL 2005SQL 2008sp_executeresultsetX  sp_MSforeachdbXXXsp_MSforeachtableXXXsp_readerrorlogXXXxp_create_subdir XXXp_delete_file XXxp_dirtreeXXXxp_fileexistXXXxp_fixeddrivesXXXxp_getfiledetailsX  xp_getnetnameXXXxp_loginconfigXXXxp_makecabX  xp_msverXXXxp_get_mapi_profilesXXXxp_subdirsXXXxp_test_mapi_profileXXXxp_unpackcabX  sp_executeresultsetMicrosoft removed this handy little procedure called sp_executeresultset from SQL Server in SQL Server 2005. It allows you to generate dynamic SQL code on the fly by using a SELECT query. Then, the resulting SQL commands will be executed against the database. It permits you to create a single piece of code that can, in a single step, find the number of records in every table in your database (as the example shows). This is an undocumented stored procedure and there is no way of knowing why it was removed. But, alas, this handy utility is gone.exec sp_execresultset 'SELECT ''SELECT '''''' + name + '''''', count(*) FROM '' + namefrom sysobjectswhere xtype = ''U'''sp_MSforeachdb / sp_MSforeachtableTwo procedures, sp_MSforeachdb and sp_MSforeachtable, are wrappers around a cursor. They allow you to execute T-SQL code against each database on your SQL Server and each table within the current database, respectively. You cannot, however, use an sp_MSforeachtable command within an sp_MSforeachdb command in SQL 2000 and prior. The cursor name that was used within those procedures was the same (hCForEach) and would therefore return an error saying that the cursor name was already in use for each execution of the sp_MSforeachtable. In SQL Server 2005, Microsoft resolved this issue. In order to "next" the command, you must tell one of the procedures it will be using a different replacement character other than the default question mark. I change the replacement character in the database command because it's easier.Print each table name in the current database.exec sp_MSforeachtable 'print ''?'''Print each database on the current server.exec sp_MSforeachdb 'print ''?'''Print each table on the current server.exec sp_MSforeachdb 'use [@] exec sp_MSforeachtable ''print''''@.?''''''', '@'sp_readerrorlog / xp_readerrorlogThe stored procedure sp_readerrorlog actually comes in two forms. Each works the same; one is simply a wrapper for the second. The wrapper stored procedure is sp_readerrorlog and it calls xp_readerrorlog. Both have four input parameters, but only the first two are useful to us. The first parameter establishes the file number that you wish to view. The second is the log to view (1 or null for ERRORLOG, 2 for SQL Agent Log). This allows you to view your error logs quickly and easily instead of having to look at the bloated log viewer that now comes with SQL Server 2005 and SQL 2008.View the current SQL ERRORLOG file.exec sp_readerrorlogexec sp_readerrorlog 0, 1View the Prior SQL Agent Log file.exec sp_readerrorlog 1, 2xp_create_subdirIntroduced in SQL Server 2005, the xp_create_subdir stored procedure is very handy because you can use it to create folders on SQL Server's hard drive or on a network share from within T-SQL.exec xp_create_subdir 'c:\MSSQL\Data'xp_delete_fileUse the xp_delete_file stored procedure introduced in SQL Server 2005 to delete files from SQL Server's hard drive or a network share from within T-SQL.xp_dirtreeThe xp_dirtree procedure allows you to view the folder tree and/or file list beneath a folder. This procedure has several parameters that control how deep the procedure searches and whether it returns files and folders or folders only. The first parameter establishes the folder to look in. (Recommendation: Do not run this procedure against the root of the drive that Windows is installed on because it will take some time to generate the tree and return the data.) The second parameter limits the number of recursive levels that the procedure will dig through. The default is zero or all levels. The third parameter tells the procedure to include files. The default is zero or folders only, a value of 1 includes files in the result set. Specifying a third value not equal to zero will add an additional column to the output called file which is a bit field showing the entry in a folder or file.Get the full directory tree.exec xp_dirtree 'd:\mssql\'Get the first two levels of the directory tree.exec xp_dirtree 'd:\mssql\', 2Get the first three levels of the directory tree, including files.exec xp_dirtree 'd:\mssql\', 3, 1xp_fileexistThis SQL Server stored procedure, xp_fileexist, is used to determine if a file exists on SQL Server's hard drive or on a network share. It is extremely useful in stored procedures that load data from flat files. It allows you to check and see if the file exists before attempting to blindly load the file. The procedure has two parameters. Use the first parameter to determine if the file or folder you want exists. The second is an output parameter, which when specified, returns a 1 or 0 if the file exists or does not.Without the parameter.exec xp_fileexist 'c:\importfile.csv'With the parameter.DECLARE @file_exists intexec xp_fileexist 'c:\importfile.csv', @file_exists OUTPUTSELECT @file_exists xp_fixeddrivesThe procedure xp_fixeddrives is one of the most useful procedures. It presents a list of all drive letters and the amount of free space each drive has. The parameter has a single optional input parameter that can filter the results by drive type. A value of 3 will return all mass storage devices (CD-ROM, DVD, etc.); a value of 4 will return the hard drives; while a value of 2 will return removable media (USB thumb drives, flash drives, etc.).Return all drives.exec xp_fixeddrivesReturn hard drives only.exec xp_fixeddrives 2xp_getfiledetailsThe procedure xp_getfiledetails is another extremely useful procedure, which was last available in SQL Server 2000. This procedure returns size, date and attribute information about the file specified, including date and times created, accessed and modified.exec xp_getfiledetails 'c:\filetoload.csv'xp_getnetnameThe procedure xp_getnetname returns the name of the physical machine where Microsoft SQL Server is installed. You can have the machine name returned as a record set or as a variable.Without the parameter.exec xp_getnetnameUsing the parameter.DECLARE @machinename sysnameexec xp_getnetname @machinename OUTPUTselect @machinename xp_loginconfigThis SQL Server stored procedure will tell you some basic authentication information about the user executing it. It tells you the authentication method (Windows versus SQL Login), the default domain of the server, the audit level, as well as some internal separator information.exec xp_loginconfigxp_makecabBack in SQL Server 2000, Microsoft gave us the ability to compress OS files directly from T-SQL without having to shell out to DOS via xp_cmdshell and run third-party software, like pkzip or winzip. That command was xp_makecab. It allows you to specify a list of files you want to compress as well as the cab file you want to put them in. It even lets you select default compression, MSZIP compression (akin to the .zip file format) or no compression. The first parameter gives the path to the cab file in which you want to create or add files to. The second parameter is the compression level. The third parameter applies if you want to use verbose logging. Starting with the fourth parameter and on down are the names of the files you want to compress. In my testing, I was able to pass 45 file names to be compressed to the extended stored procedure, which means that it is a very flexible solution to your data compression requirements.exec xp_makecab 'c:\test.cab', 'mszip', 1, 'c:\test.txt' , 'c:\test1.txt'xp_msverThe procedure xp_msver is very useful when looking for system information. It returns a wealth of information about the host operating system -- the SQL version number, language, CPU type, copyright and trademark information, Microsoft Windows version, CPU count and affinity settings, physical memory settings and your product key. This procedure has many input parameters that allow you to filter down the records that are returned. Each parameter is a sysname data type, which accepts the name of one of the records. If any parameters are specified, only the rows specified as a parameter are returned.No filter specified.exec xp_msverReturn only Platform and Comments records.exec xp_msver 'Platform', 'Comments'xp_get_mapi_profilesThe xp_get_mapi_profiles procedure assists you in configuring SQL Mail. When executed, it will call to Windows via the SQL Mail component of SQL Server and display a list of available MAPI profiles that are configured in Outlook and it specifies which profile is the default profile. If it doesn't display any records, then either Outlook is not configured correctly or SQL Server is not running under a domain account with Outlook profiles configured. In order to use this procedure in SQL Server 2005 or SQL Server 2008, you must enable the "SQL Mail XPs" option in the Surface Area Configuration tool or within the sp_configure procedure.exec xp_get_mapi_profilesxp_subdirsThe xp_subdirs procedure displays a subset of the information avaialble through xp_dirtree. Xp_subdirs will display all the subfolders in a given folder. It can be very handy when you are building a directory tree within a table dynamically and you do not want to worry about the extra parameters of the xp_dirtree procedure.exec xp_subdirs 'd:\mssql'xp_test_mapi_profilesThe procedure xp_test_mapi_profiles is another undocumented stored procedure that is very useful when you are setting up SQL Mail. It will start, then stop, a MAPI session to ensure that MAPI is configured correctly and working within the confines of Microsoft SQL Server. I should note that it does not verify the mail server configuration within the MAPI client (Outlook) nor does it send a test message.The procedure accepts a single input parameter. That parameter is the name of the MAPI profile you wish to test. Like the xp_get_mapi_profiles procedure, for this stored procedure to function in SQL Server 2005 and SQL Server 2008, you must enable the "SQL Mail XPs" option in the Surface Area Configuration tool or within the sp_configure procedure.When working with the SQL Mail stored procedures, be aware that SQL Mail is still slated for removal from the Microsoft SQL Server platform. That means the procedures sp_get_mapi_profiles and xp_test_mapi_profiles are slated for removal, as they are part of the SQL Mail subsystem. You should do all mail work on SQL Server 2005 and later using Database Mail instead of SQL Mail to ensure code portability with future versions of SQL Server. Microsoft initially slated SQL Mail for removal in SQL Server 2008, however, based on its inclusion in the current beta release, its future in SQL Server 2008 is unknown.xp_unpackcabAlong with the xp_makecab procedure comes the xp_unpackcab extended stored procedure, and it does just what it says: It extracts files from cab files. The first paramater is the cab file, the second is the path you want to extract to and the third is verbose logging. A fourth paramater lets you specify the "extract to" file name.exec xp_unpackcab 'c:\test.cab', 'c:\temp\', 1While this is not intended to be a complete list of the undocumented stored procedures in SQL Server, it does provide a reference point for many of these procedures with the hope of making the lives of the SQL Server administrators easier. Remember, you should never count on these procedures surviving from one SQL Server version to the next, nor should you expect their code base to remain the same between versions. That said,

学生表:create table student( id number(8) primary key, name varchar2(10),deptment number(8))选课表:create table select_course(  ID         NUMBER(8) primary key,  STUDENT_ID NUMBER(8) foreign key (COURSE_ID) references course(ID),  COURSE_ID  NUMBER(8) foreign key (STUDENT_ID) references student(ID))课程表:create table COURSE(  ID     NUMBER(8) not null,  C_NAME VARCHAR2(20),  C_NO   VARCHAR2(10))student表的数据:        ID NAME            DEPTMENT_ID---------- --------------- -----------         1 echo                   1000         2 spring                 2000         3 smith                  1000         4 liter                  2000course表的数据:        ID C_NAME               C_NO---------- -------------------- --------         1 数据库               data1         2 数学                 month1         3 英语                 english1select_course表的数据:        ID STUDENT_ID  COURSE_ID---------- ---------- ----------         1          1          1         2          1          2         3          1          3         4          2          1         5          2          2         6          3          21.查询选修了所有课程的学生id、name:(即这一个学生没有一门课程他没有选的。)分析:如果有一门课没有选,则此时(1)select * from select_course sc where sc.student_id=ts.id and sc.course_id=c.id存在null,这说明(2)select * from course c 的查询结果中确实有记录不存在(1查询中),查询结果返回没有选的课程,此时select * from t_student ts 后的not exists 判断结果为false,不执行查询。SQL> select * from t_student ts where not exists  (select * from course c where not exists   (select * from select_course sc where sc.student_id=ts.id and sc.course_id=c.id));                ID NAME            DEPTMENT_ID---------- --------------- -----------         1 echo                   10002.查询没有选择所有课程的学生,即没有全选的学生。(存在这样的一个学生,他至少有一门课没有选),分析:只要有一个门没有选,即select * from select_course sc where student_id=t_student.id and course_id=course.id 有一条为空,即not exists null 为true,此时select * from course有查询结果(id为子查询中的course.id ),因此select id,name from t_student 将执行查询(id为子查询中t_student.id )。SQL> select id,name from t_student where exists (select * from course where not exists (select * from select_course sc where student_id=t_student.id and course_id=course.id));        ID NAME---------- ---------------         2 spring         3 smith         4 liter3.查询一门课也没有选的学生。(不存这样的一个学生,他至少选修一门课程),分析:如果他选修了一门select * from course结果集不为空,not exists 判断结果为false;select id,name from t_student 不执行查询。SQL> select id,name from t_student where not exists (select * from course where exists (select * from select_course sc where student_id=t_student.id and course_id=course.id));        ID NAME---------- ---------------         4 liter4.查询至少选修了一门课程的学生。SQL> select id,

开启mysql的远程访问权限默认mysql的用户是没有远程访问的权限的,因此当程序跟数据库不在同一台服务器上时,我们需要开启mysql的远程访问权限。主流的有两种方法,改表法和授权法。相对而言,改表法比较容易一点,个人也是比较倾向于使用这种方法,因此,这里只贴出改表法1、登陆mysqlmysql -u root -p 2、修改mysql库的user表,将host项,从localhost改为%。%这里表示的是允许任意host访问,如果只允许某一个ip访问,则可改为相应的ip,比如可以将localhost改为192.168.1.123,这表示只允许局域网的192.168.1.123这个ip远程访问mysql。 mysql> use mysql; mysql> update user set host = '%' where user = 'root'; mysql> select host, user from user; mysql> flush privileges;防火墙开放3306端口1、打开防火墙配置文件vi /etc/sysconfig/iptables 2、增加下面一行-A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT 3、重启防火墙service iptables restart 注意:增加的开放3306端口的语句一定要在icmp-host-prohibited之前附:个人配置# Firewall configuration written by system-config-firewall# Manual customization of this file is not recommended.*filter:INPUT ACCEPT [0:0]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [0:0]-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT-A INPUT -p icmp -j ACCEPT-A INPUT -i lo -j ACCEPT-A INPUT -i eth0 -j ACCEPT-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT-A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT-A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT-A FORWARD -p icmp -j ACCEPT-A FORWARD -i lo -j ACCEPT-A FORWARD -i eth0 -j ACCEPT-A INPUT -j REJECT --reject-with icmp-host-prohibited-A FORWARD -j REJECT --reject-with icmp-host-prohibitedCOMMIT以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

刚开始,根据我的想法,这个很简单嘛,上sql语句delete from zqzrdp where tel in (select min(dpxx_id) from zqzrdp group by tel having count(tel)>1);执行,报错!!~!~异常意为:你不能指定目标表的更新在FROM子句。傻了,MySQL 这样写,不行,让人郁闷。难倒只能分步操作,蛋疼以下是网友写的,同样是坑爹的代码,我机器上运行不了。1. 查询需要删除的记录,会保留一条记录。select a.id,a.subject,a.RECEIVER from test1 a left join (select c.subject,c.RECEIVER ,max(c.id) as bid from test1 c where status=0 GROUP BY RECEIVER,SUBJECT having count(1) >1) b on a.id< b.bid where a.subject=b.subject and a.RECEIVER = b.RECEIVER and a.id < b.bid2. 删除重复记录,只保留一条记录。注意,subject,RECEIVER 要索引,否则会很慢的。delete a from test1 a, (select c.subject,c.RECEIVER ,max(c.id) as bid from test1 c where status=0 GROUP BY RECEIVER,SUBJECT having count(1) >1) b where a.subject=b.subject and a.RECEIVER = b.RECEIVER and a.id < b.bid;3. 查找表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断select * from people where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)4. 删除表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断,只留有rowid最小的记录delete from people where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1) and rowid not in (select min(rowid) from people group by peopleId having count(peopleId )>1)5.删除表中多余的重复记录(多个字段),只留有rowid最小的记录delete from vitae a where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1) and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1)看来想偷懒使用一句命令完成这个事好像不太显示,还是老老实实的分步处理吧,思路先建立复制一个临时表,然后对比临时表内的数据,删除主表里的数据alter table tableName add autoID int auto_increment not null; create table tmp select min(autoID) as autoID from tableName group by Name,Address; create table tmp2 select tableName.* from tableName,

焦点访谈

最新最热的文章

更多 >

COPYRIGHT (©) 2017 Copyright ©2017 5060网址大全 网站地图

联系我们

827570882

扫描二维码分享到微信