<?xml version="1.0" standalone="yes"?>
<?xml-stylesheet type="text/xsl" href="css/rss.xslt"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title> - SQL</title><link>http://www.chinacmcc.com/</link><description>I did my way.That's my way.  - </description><generator>RainbowSoft Studio Z-Blog 1.8 Walle Build 100427</generator><language>zh-CN</language><copyright>赣ICP备06002279号 Powered By Z-Blog 1.8 This site is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License.</copyright><pubDate>Sun, 05 Sep 2010 17:44:49 +0800</pubDate><item><title>[SQL学习]ORA-03114解决办法</title><author>a@b.com (walker)</author><link>http://www.chinacmcc.com/post/22.html</link><pubDate>Thu, 28 Jan 2010 19:49:12 +0800</pubDate><guid>http://www.chinacmcc.com/post/22.html</guid><description><![CDATA[<p>最近在使用PL/SQL时经常遇到ORA-03114报错，然后程序就变得不可调试了，不能停止，只能重启PL/SQL才能继续使用，比较繁琐，在网上搜了下，找到两个解决办法：</p><p>方法一：</p><p>在使用pl/sql developer的时候老是报错，让dba给看了一下，dba给搞定了，现在分享给大家。<br /><span class="t_tag" onclick="tagshow(event)" href="tag.php?name=%BD%E2%BE%F6">解决</span>方法;<br /><br /><font face="宋体 "><font size="2">&nbsp;&nbsp;这是我们使用的<span class="t_tag" onclick="tagshow(event)" href="tag.php?name=%BF%CD%BB%A7">客户</span>端<span class="t_tag" onclick="tagshow(event)" href="tag.php?name=%B9%A4%BE%DF">工具</span> </font><font size="3">Pl/Sql developer 和<span class="t_tag" onclick="tagshow(event)" href="tag.php?name=%CA%FD%BE%DD%BF%E2">数据库</span>的cdc产生冲突，如果使用TOAD等其他客户端工具则不会有这种情况。</font></font><br /><font face="宋体 ">&nbsp; &nbsp;还需要大家在<span class="t_tag" onclick="tagshow(event)" href="tag.php?name=%BF%AA%B7%A2">开发</span>中留意：</font><br /><font face="宋体 ">&nbsp; &nbsp;1，用Pl/Sql developer是否还会发生编译不过的情况。</font><br /><font face="宋体 ">&nbsp; &nbsp;2，是否会导致其他问题。</font><br /><font face="宋体 ">&nbsp; &nbsp;谢谢！</font><br /><font face="宋体 ">&nbsp;&nbsp;&nbsp;</font><br /><font face="宋体 ">解决方法为：去掉cdc<span class="t_tag" onclick="tagshow(event)" href="tag.php?name=%B9%A6%C4%DC">功能</span>。</font><br /><font face="宋体 ">操作为：</font><br />DROP TRIGGER sys.cdc_alter_ctable_before;<br />DROP TRIGGER sys.cdc_create_ctable_after;<br />DROP TRIGGER sys.cdc_create_ctable_before ;<br />DROP TRIGGER sys.cdc_drop_ctable_before;<br />CALL sys.dbms_java.dropjava('-s rdbms/jlib/CDC.jar');</p><p><br />这是oracle的信息：<br />ORA-03114 not connected to <span class="t_tag" onclick="tagshow(event)" href="tag.php?name=ORACLE">ORACLE</span><br /><br />Cause: A call to Oracle was attempted when no connection was established. Usually this happens because a user-written program has not logged on. It may happen if communication trouble causes a disconnection. In addition, this message could occur when ALTER SYSTEM KILL SESSION or ALTER SYSTEM DISCONNECT SESSION were issued with the IMMEDIATE qualifier because, in those cases, the client's connection to the database is terminated without waiting for the client to issue a request.<br /><br />Action: Try again. If the message recurs and the program is user written, check the program.</p><p>&nbsp;</p><p>方法二：<br />在PL/SQL中改一个设置：</p><p>&nbsp;</p><p><img title="" alt="" src="http://www.chinacmcc.com/upload/2010/1/201001282121424825.png" onload="ResizeImage(this,0)" /></p>]]></description><category>SQL</category><comments>http://www.chinacmcc.com/post/22.html#comment</comments><wfw:comment>http://www.chinacmcc.com/</wfw:comment><wfw:commentRss>http://www.chinacmcc.com/feed.asp?cmt=22</wfw:commentRss><trackback:ping>http://www.chinacmcc.com/cmd.asp?act=tb&amp;id=22&amp;key=8322764c</trackback:ping></item><item><title>[SQL学习]Oracle维护常用SQL语句汇总</title><author>a@b.com (walker)</author><link>http://www.chinacmcc.com/post/21.html</link><pubDate>Mon, 03 Aug 2009 11:33:57 +0800</pubDate><guid>http://www.chinacmcc.com/post/21.html</guid><description><![CDATA[<p>如何远程判断<a onclick="javascript:tagshow(event, 'Oracle');" href="javascript:;" target="_self"><u><strong>Oracle</strong></u></a><a onclick="javascript:tagshow(event, '%CA%FD%BE%DD%BF%E2');" href="javascript:;" target="_self"><u><strong>数据库</strong></u></a>的<a onclick="javascript:tagshow(event, '%B0%B2%D7%B0');" href="javascript:;" target="_self"><u><strong>安装</strong></u></a>平台<br /><br />select * from v$version;<br /><br />查看表空间的使用情况<br /><br />select sum(bytes)/(1024*1024) as free_space,tablespace_name<br />from dba_free_space<br />group by tablespace_name;<br /><br /><br />SELECT A.TABLESPACE_NAME,A.BYTES TOTAL,B.BYTES USED, C.BYTES FREE,<br />(B.BYTES*100)/A.BYTES &quot;% USED&quot;,(C.BYTES*100)/A.BYTES &quot;% FREE&quot;<br />FROM SYS.SM$TS_AVAIL A,SYS.SM$TS_USED B,SYS.SM$TS_FREE C<br />WHERE A.TABLESPACE_NAME=B.TABLESPACE_NAME AND A.TABLESPACE_NAME=C.TABLESPACE_NAME;<br /><br />&nbsp;</p><p>1、查看表空间的名称及大小<br /><br />select t.tablespace_name, round(sum(bytes/(1024*1024)),0) ts_size<br />from dba_tablespaces t, dba_data_files d<br />where t.tablespace_name = d.tablespace_name<br />group by t.tablespace_name;<br /><br /><br />2、查看表空间物理文件的名称及大小<br /><br />select tablespace_name, file_id, file_name,<br />round(bytes/(1024*1024),0) total_space<br />from dba_data_files<br />order by tablespace_name;<br /><br /><br />3、查看回滚段名称及大小<br /><br />select segment_name, tablespace_name, r.status,<br />(initial_extent/1024) InitialExtent,(next_extent/1024) NextExtent,<br />max_extents, v.curext CurExtent<br />From dba_rollback_segs r, v$rollstat v<br />Where r.segment_id = v.usn(+)<br />order by segment_name ;<br /><br /><br />4、查看控制文件<br /><br />select name from v$controlfile;<br /><br /><br />5、查看日志文件<br /><br />select member from v$logfile;<br /><br /><br />6、查看表空间的使用情况<br /><br />select sum(bytes)/(1024*1024) as free_space,tablespace_name<br />from dba_free_space<br />group by tablespace_name;<br /><br /><br />SELECT A.TABLESPACE_NAME,A.BYTES TOTAL,B.BYTES USED, C.BYTES FREE,<br />(B.BYTES*100)/A.BYTES &quot;% USED&quot;,(C.BYTES*100)/A.BYTES &quot;% FREE&quot;<br />FROM SYS.SM$TS_AVAIL A,SYS.SM$TS_USED B,SYS.SM$TS_FREE C<br />WHERE A.TABLESPACE_NAME=B.TABLESPACE_NAME AND A.TABLESPACE_NAME=C.TABLESPACE_NAME;<br /><br /><br />7、查看数据库库对象<br /><br />select owner, object_type, status, count(*) count# from all_objects group by owner, object_type, status;<br /><br /><br />8、查看数据库的版本　<br /><br />Select version FROM Product_component_version<br />Where SUBSTR(PRODUCT,1,6)='Oracle';<br /><br />9、查看数据库的创建日期和归档方式<br /><br />Select Created, Log_Mode, Log_Mode From V$Database;<br /><br />10、如何远程判断Oracle数据库的安装平台<br /><br />select * from v$version;<br /><br />11、查看数据表的参数信息<br /><br />SELECT partition_name, high_value, high_value_length, tablespace_name,<br />pct_free, pct_used, ini_trans, max_trans, initial_extent,<br />next_extent, min_extent, max_extent, pct_increase, FREELISTS,<br />freelist_groups, LOGGING, BUFFER_POOL, num_rows, blocks,<br />empty_blocks, avg_space, chain_cnt, avg_row_len, sample_size,<br />last_analyzed<br />FROM dba_tab_partitions<br />--WHERE table_name = :tname AND table_owner = :towner<br />ORDER BY partition_position<br /><br /><br />12、查看还没提交的事务<br /><br />select * from v$locked_object;<br />select * from v$transaction;<br /><br /><br />14、回滚段查看<br /><br />select rownum, sys.dba_rollback_segs.segment_name Name, v$rollstat.extents<br />Extents, v$rollstat.rssize Size_in_Bytes, v$rollstat.xacts XActs,<br />v$rollstat.gets Gets, v$rollstat.waits Waits, v$rollstat.writes Writes,<br />sys.dba_rollback_segs.status status from v$rollstat, sys.dba_rollback_segs,<br />v$rollname where v$rollname.name(+) = sys.dba_rollback_segs.segment_name and<br />v$rollstat.usn (+) = v$rollname.usn order by rownum<br />&nbsp;</p><p>15、捕捉运行很久的<a onclick="javascript:tagshow(event, 'SQL');" href="javascript:;" target="_self"><u><strong>SQL</strong></u></a><br /><br />column username format a12<br />column opname format a16<br />column progress format a8<br /><br />select username,sid,opname,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; round(sofar*100 / totalwork,0) || '%' as progress,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; time_remaining,sql_text<br />from v$session_longops , v$sql<br />where time_remaining &lt;&gt; 0<br />and sql_address = address<br />and sql_hash_value = hash_value<br />/<br />16。查看数据表的参数信息<br />SELECT&nbsp;&nbsp; partition_name, high_value, high_value_length, tablespace_name,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; pct_free, pct_used, ini_trans, max_trans, initial_extent,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; next_extent, min_extent, max_extent, pct_increase, FREELISTS,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; freelist_groups, LOGGING, BUFFER_POOL, num_rows, blocks,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; empty_blocks, avg_space, chain_cnt, avg_row_len, sample_size,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; last_analyzed<br />&nbsp;&nbsp; FROM dba_tab_partitions<br />&nbsp; --WHERE table_name = :tname AND table_owner = :towner<br />ORDER BY partition_position<br /><br />17。查找object为哪些进程所用<br />select<br />p.spid,<br />s.sid,<br />s.serial# serial_num,<br />s.username user_name,<br />a.type&nbsp; object_type,<br />s.osuser os_user_name,<br />a.owner,<br />a.object object_name,<br />decode(sign(48 - command),<br />1,<br />to_char(command), 'Action Code #' || to_char(command) ) action,<br />p.program oracle_process,<br />s.terminal terminal,<br />s.program program,<br />s.status session_status&nbsp;<br />from v$session s, v$access a, v$process p&nbsp;<br />where s.paddr = p.addr and<br />&nbsp;&nbsp;&nbsp;&nbsp; s.type = 'USER' and&nbsp;&nbsp;&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp; a.sid = s.sid&nbsp;&nbsp; and<br />&nbsp; a.object='SUBSCRIBER_ATTR'<br />order by s.username, s.osuser<br /><br />18。耗资源的进程（top session）<br />select s.schemaname schema_name,&nbsp;&nbsp;&nbsp; decode(sign(48 - command), 1,<br />to_char(command), 'Action Code #' || to_char(command) ) action,&nbsp;&nbsp;&nbsp; status<br />session_status,&nbsp;&nbsp; s.osuser os_user_name,&nbsp;&nbsp; s.sid,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; p.spid ,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; s.serial# serial_num,&nbsp;<br />nvl(s.username, '[Oracle process]') user_name,&nbsp;&nbsp; s.terminal terminal,&nbsp;&nbsp;&nbsp;<br />s.program program,&nbsp;&nbsp; st.value criteria_value&nbsp; from v$sesstat st,&nbsp;&nbsp; v$session s&nbsp; , v$process p&nbsp;<br />where st.sid = s.sid and&nbsp;&nbsp; st.statistic# = to_number('38') and&nbsp;&nbsp; ('ALL' = 'ALL'<br />or s.status = 'ALL') and p.addr = s.paddr order by st.value desc,&nbsp; p.spid asc, s.username asc, s.osuser asc<br /><br />19。查看锁（lock）情况<br />select /*+ RULE */ ls.osuser os_user_name,&nbsp;&nbsp; ls.username user_name,&nbsp;<br />decode(ls.type, 'RW', 'Row wait enqueue lock', 'TM', 'DML enqueue lock', 'TX',<br />'Transaction enqueue lock', 'UL', 'User supplied lock') lock_type,&nbsp;<br />o.object_name object,&nbsp;&nbsp; decode(ls.lmode, 1, null, 2, 'Row Share', 3,<br />'Row Exclusive', 4, 'Share', 5, 'Share Row Exclusive', 6, 'Exclusive', null)<br />lock_mode,&nbsp;&nbsp;&nbsp; o.owner,&nbsp;&nbsp; ls.sid,&nbsp;&nbsp; ls.serial# serial_num,&nbsp;&nbsp; ls.id1,&nbsp;&nbsp; ls.id2&nbsp;&nbsp;&nbsp;<br />from sys.dba_objects o, (&nbsp;&nbsp; select s.osuser,&nbsp;&nbsp;&nbsp; s.username,&nbsp;&nbsp;&nbsp; l.type,&nbsp;&nbsp;&nbsp;<br />l.lmode,&nbsp;&nbsp;&nbsp; s.sid,&nbsp;&nbsp;&nbsp; s.serial#,&nbsp;&nbsp;&nbsp; l.id1,&nbsp;&nbsp;&nbsp; l.id2&nbsp;&nbsp; from v$session s,&nbsp;&nbsp;&nbsp;<br />v$lock l&nbsp;&nbsp; where s.sid = l.sid ) ls&nbsp; where o.object_id = ls.id1 and&nbsp;&nbsp;&nbsp; o.owner<br />&lt;&gt; 'SYS'&nbsp;&nbsp; order by o.owner, o.object_name<br />&nbsp;</p><p>根据sid查是哪台电脑的链接<br />column osuser format a15<br />column username format a10<br />column machine format a30<br />select osuser,machine,username,sid,serial# from v$session where sid='128';</p><p>根据sid查对应的sql<br />select SID,SQL_TEXT from v$open_cursor where SID='128';</p><p>20。查看等待（wait）情况<br />SELECT v$waitstat.class, v$waitstat.count count, SUM(v$sysstat.value) sum_value<br />FROM v$waitstat, v$sysstat WHERE v$sysstat.name IN ('db block gets',<br />'consistent gets') group by v$waitstat.class, v$waitstat.count<br /><br />21。查看sga情况<br />SELECT NAME, BYTES FROM SYS.V_$SGASTAT ORDER BY NAME ASC<br /><br />22。查看catched object<br />SELECT owner,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; name,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; db_link,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; namespace,&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; type,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sharable_mem,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; loads,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; executions,&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; locks,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; pins,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; kept&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; FROM v$db_object_cache<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />23。查看V$SQLAREA<br />SELECT SQL_TEXT, SHARABLE_MEM, PERSISTENT_MEM, RUNTIME_MEM, SORTS,<br />VERSION_COUNT, LOADED_VERSIONS, OPEN_VERSIONS, USERS_OPENING, EXECUTIONS,<br />USERS_EXECUTING, LOADS, FIRST_LOAD_TIME, INVALIDATIONS, PARSE_CALLS, DISK_READS,<br />BUFFER_GETS, ROWS_PROCESSED FROM V$SQLAREA<br /><br />24。查看object分类数量<br />select decode (o.type#,1,'INDEX' , 2,'TABLE' , 3 , 'CLUSTER' , 4, 'VIEW' , 5 ,<br />'SYNONYM' , 6 , 'SEQUENCE' , 'OTHER' ) object_type , count(*) quantity from<br />sys.obj$ o where o.type# &gt; 1 group by decode (o.type#,1,'INDEX' , 2,'TABLE' , 3<br />, 'CLUSTER' , 4, 'VIEW' , 5 , 'SYNONYM' , 6 , 'SEQUENCE' , 'OTHER' ) union select<br />'COLUMN' , count(*) from sys.col$ union select 'DB LINK' , count(*) from<br /><br />25。按用户查看object种类<br />select u.name schema,&nbsp;&nbsp; sum(decode(o.type#, 1, 1, NULL)) indexes,&nbsp;<br />sum(decode(o.type#, 2, 1, NULL)) tables,&nbsp;&nbsp; sum(decode(o.type#, 3, 1, NULL))<br />clusters,&nbsp;&nbsp; sum(decode(o.type#, 4, 1, NULL)) views,&nbsp;&nbsp; sum(decode(o.type#, 5, 1,<br />NULL)) synonyms,&nbsp;&nbsp; sum(decode(o.type#, 6, 1, NULL)) sequences,&nbsp;<br />sum(decode(o.type#, 1, NULL, 2, NULL, 3, NULL, 4, NULL, 5, NULL, 6, NULL, 1))<br />others&nbsp;&nbsp; from sys.obj$ o, sys.user$ u&nbsp;&nbsp; where o.type# &gt;= 1 and&nbsp;&nbsp;&nbsp; u.user# =<br />o.owner# and&nbsp;&nbsp; u.name &lt;&gt; 'PUBLIC'&nbsp;&nbsp; group by u.name&nbsp;&nbsp;&nbsp; order by<br />sys.link$ union select 'CONSTRAINT' , count(*) from sys.con$<br /><br />26。有关connection的相关信息<br />1）查看有哪些用户连接<br />select s.osuser os_user_name,&nbsp;&nbsp;&nbsp; decode(sign(48 - command), 1, to_char(command),<br />'Action Code #' || to_char(command) ) action,&nbsp;&nbsp;&nbsp;&nbsp; p.program oracle_process,&nbsp;&nbsp;&nbsp;<br />status session_status,&nbsp;&nbsp;&nbsp; s.terminal terminal,&nbsp;&nbsp;&nbsp; s.program program,&nbsp;&nbsp;&nbsp;<br />s.username user_name,&nbsp;&nbsp;&nbsp; s.fixed_table_sequence activity_meter,&nbsp;&nbsp;&nbsp; '' query,&nbsp;&nbsp;&nbsp;<br />0 memory,&nbsp;&nbsp;&nbsp; 0 max_memory,&nbsp;&nbsp;&nbsp;&nbsp; 0 cpu_usage,&nbsp;&nbsp;&nbsp; s.sid,&nbsp;&nbsp; s.serial# serial_num&nbsp;&nbsp;&nbsp;<br />from v$session s,&nbsp;&nbsp;&nbsp; v$process p&nbsp;&nbsp; where s.paddr=p.addr and&nbsp;&nbsp;&nbsp; s.type = 'USER'&nbsp;<br />order by s.username, s.osuser<br />2）根据v.sid查看对应连接的资源占用等情况<br />select n.name,<br />&nbsp;v.value,<br />&nbsp;n.class,<br />&nbsp;n.statistic#&nbsp;<br />from&nbsp; v$statname n,<br />&nbsp;v$sesstat v<br />where v.sid = 71 and<br />&nbsp;v.statistic# = n.statistic#<br />order by n.class, n.statistic#<br />3）根据sid查看对应连接正在运行的sql<br />select /*+ PUSH_SUBQ */<br />&nbsp;command_type,<br />&nbsp;sql_text,<br />&nbsp;sharable_mem,<br />&nbsp;persistent_mem,<br />&nbsp;runtime_mem,<br />&nbsp;sorts,<br />&nbsp;version_count,<br />&nbsp;loaded_versions,<br />&nbsp;open_versions,<br />&nbsp;users_opening,<br />&nbsp;executions,<br />&nbsp;users_executing,<br />&nbsp;loads,<br />&nbsp;first_load_time,<br />&nbsp;invalidations,<br />&nbsp;parse_calls,<br />&nbsp;disk_reads,<br />&nbsp;buffer_gets,<br />&nbsp;rows_processed,<br />&nbsp;sysdate start_time,<br />&nbsp;sysdate finish_time,<br />&nbsp;'&gt;' || address sql_address,<br />&nbsp;'N' status<br />from v$sqlarea<br />where address = (select sql_address from v$session where sid = 71)<br /><br />27．查询表空间使用情况<br />select a.tablespace_name &quot;表空间名称&quot;,<br />100-round((nvl(b.bytes_free,0)/a.bytes_alloc)*100,2) &quot;占用率(%)&quot;,<br />round(a.bytes_alloc/1024/1024,2) &quot;容量(M)&quot;,<br />round(nvl(b.bytes_free,0)/1024/1024,2) &quot;空闲(M)&quot;,<br />round((a.bytes_alloc-nvl(b.bytes_free,0))/1024/1024,2) &quot;使用(M)&quot;,<br />Largest &quot;最大扩展段(M)&quot;,<br />to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') &quot;采样时间&quot;<br />from&nbsp; (select f.tablespace_name,<br />&nbsp;&nbsp; sum(f.bytes) bytes_alloc,<br />&nbsp;&nbsp; sum(decode(f.autoextensible,'YES',f.maxbytes,'NO',f.bytes)) maxbytes<br />from dba_data_files f<br />group by tablespace_name) a,<br />(select&nbsp; f.tablespace_name,<br />&nbsp;&nbsp;&nbsp; sum(f.bytes) bytes_free<br />from dba_free_space f<br />group by tablespace_name) b,<br />(select round(max(ff.length)*16/1024,2) Largest,<br />&nbsp;&nbsp; ts.name tablespace_name<br />from sys.fet$ ff, sys.file$ tf,sys.ts$ ts<br />where ts.ts#=ff.ts# and ff.file#=tf.relfile# and ts.ts#=tf.ts#<br />group by ts.name, tf.blocks) c<br />where a.tablespace_name = b.tablespace_name and a.tablespace_name = c.tablespace_name<br /><br />28. 查询表空间的碎片程度<br /><br />select tablespace_name,count(tablespace_name) from dba_free_space group by tablespace_name<br />having count(tablespace_name)&gt;10;<br /><br />alter tablespace name coalesce;<br />alter table name deallocate unused;<br /><br />create or replace view ts_blocks_v as<br />select tablespace_name,block_id,bytes,blocks,'free space' segment_name from dba_free_space<br />union all<br />select tablespace_name,block_id,bytes,blocks,segment_name from dba_extents;<br /><br />select * from ts_blocks_v;<br /><br />select tablespace_name,sum(bytes),max(bytes),count(block_id) from dba_free_space<br />group by tablespace_name;<br /><br />29。查询有哪些数据库实例在运行<br />select inst_name from v$active_instances;</p><p>30. 查找oracle性能瓶颈sql<br /><br />select sql_text,spid,v$session.program,process from<br />v$sqlarea,v$session,v$process<br />where v$sqlarea.address=v$session.sql_address<br />and v$sqlarea.hash_value=v$session.sql_hash_value<br />and v$session.paddr=v$process.addr<br />and v$process.spid in (操作系统PID);<br /><br /><br />select sid,event,p1,p1text from v$session_wait;<br /><br />31. 找出最耗资源的sql<br /><br /><span class="unnamed3">select * from v$process where spid='2796';<br /><br />select sql_hash_value,machine,username,program from v$session where PAddr='63B7A584';<br /><br />select * from v$sqltext where hash_value='833203018';<br /><br />select * from v$sql where hash_value='833203018';<br /><br />select * from v$sqlarea where hash_value='833203018';<br /><br />SELECT a.username,a.machine,a.program,a.sid,a.serial#,a.status,c.piece,c.sql_text FROM v$session a,v$process b,v$sqltext c WHERE b.spid='2796' AND b.addr=a.paddr AND a.sql_address=c.address(+) ORDER BY c.piece</span><span class="unnamed3">要找出最耗资源的sql，我们可以首先使用top等工具，找到最好资源的进程（记住进程号），例如，操作<a onclick="javascript:tagshow(event, '%CF%B5%CD%B3');" href="javascript:;" target="_self"><u><strong>系统</strong></u></a>进程号为</span><span class="unnamed3">2796</span><span class="unnamed3">，然后根据这个进程号(v$process.spid)在v$process中找到进程地址(v$process.addr)，然后根据这个地址在 v$session中找到相应的sid(v$session.sid)，然后根据这个sid找到相应的hash alue（v$session. sql_hash_value），然后根据这个hash alue在v$sqltext，$sql，v$sqlarea等视图中找到对应的sql语句（sql_text）。<br /><br />select * from v$process where spid='2796';<br /><br />select sql_hash_value,machine,username,program from v$session where PAddr='63B7A584';<br /><br />select * from v$sqltext where hash_value='833203018';<br /><br />select * from v$sql where hash_value='833203018';<br /><br />select * from v$sqlarea where hash_value='833203018';<br /><br />SELECT a.username,a.machine,a.program,a.sid,a.serial#,a.status,c.piece,c.sql_text FROM v$session a,v$process b,v$sqltext c WHERE b.spid='2796' AND b.addr=a.paddr AND a.sql_address=c.address(+) ORDER BY c.piece</span></p>]]></description><category>SQL</category><comments>http://www.chinacmcc.com/post/21.html#comment</comments><wfw:comment>http://www.chinacmcc.com/</wfw:comment><wfw:commentRss>http://www.chinacmcc.com/feed.asp?cmt=21</wfw:commentRss><trackback:ping>http://www.chinacmcc.com/cmd.asp?act=tb&amp;id=21&amp;key=652a9102</trackback:ping></item><item><title>[SQL学习]从一条select语句看Oracle数据库查询工作原理 </title><author>a@b.com (walker)</author><link>http://www.chinacmcc.com/post/20.html</link><pubDate>Mon, 20 Jul 2009 10:04:34 +0800</pubDate><guid>http://www.chinacmcc.com/post/20.html</guid><description><![CDATA[<p><span style="color: #000000" twffan="done"><span style="color: #000000" twffan="done">　　</span>假如，我们现在利用Select语句从数据库查询数据，<a class="channel_keylink" href="http://oracle.chinaitlab.com/" target="_blank"><font size="3">Oracle</font></a>数据库是如何运作的呢?从中我们可以领悟到什么呢?下面，就结合一条简单的select语句，看看<a class="channel_keylink" href="http://oracle.chinaitlab.com/" target="_blank"><font size="3">Oracle</font></a>数据库后台的运作机制。这对于我们之后的系统管理与故障排除非常有帮助。</span></p><p><span style="color: #000000" twffan="done">　　<strong>第一步：客户端把语句发给<a class="channel_keylink" href="http://server.chinaitlab.com/" target="_blank"><font size="3">服务器</font></a>端执行。</strong></span></p><p><span style="color: #000000" twffan="done">　　当我们在客户端执行select语句时，客户端会把这条SQL语句发送给<a class="channel_keylink" href="http://server.chinaitlab.com/" target="_blank"><font size="3">服务器</font></a>端，让服务器端的进程来处理这语句。也就是说，Oracle客户端是不会做任何的操作，他的主要任务就是把客户端产生的一些SQL语句发送给服务器端。虽然在客户端也有一个数据库进程，但是，这个进程的作用跟服务器上的进程作用事不相同的。服务器上的数据库进程才会对SQL语句进行相关的处理。不过，有个问题需要说明，就是客户端的进程跟服务器的进程是一一对应的。也就是说，在客户端连接上服务器后，在客户端与服务器端都会形成一个进程，客户端上的我们叫做客户端进程;而服务器上的我们叫做服务器进程。所以，由于所有的SQL语句都是服务器进程执行的，所以，有些人把服务器进程形象地比喻成客户端进程的&ldquo;影子&rdquo;。</span></p><p><span style="color: #000000" twffan="done">　　<strong>第二步：语句解析。</strong></span></p><p><span style="color: #000000" twffan="done">　　当客户端把SQL语句传送到服务器后，服务器进程会对该语句进行解析。同理，这个解析的工作，也是在服务器端所进行的。虽然这只是一个解析的动作，但是，其会做很多&ldquo;小动作&rdquo;。</span></p><p><span style="color: #000000" twffan="done">　　1、查询高速缓存。服务器进程在接到客户端传送过来的SQL语句时，不会直接去数据库查询。而是会先在数据库的高速缓存中去查找，是否存在相同语句的执行计划。如果在数据高速缓存中，刚好有其他人使用这个查询语句的话，则服务器进程就会直接执行这个SQL语句，省去后续的工作。所以，采用高速数据缓存的话，可以提高SQL语句的查询效率。一方面是从内存中读取数据要比从硬盘中的数据文件中读取数据效率要高，另一方面，也是因为这个语句解析的原因。</span></p><p><span style="color: #000000" twffan="done">　　不过这里要注意一点，这个数据缓存跟有些客户端软件的数据缓存是两码事。有些客户端软件为了提高查询效率，会在应用软件的客户端设置数据缓存。由于这些数据缓存的存在，可以提高客户端应用软件的查询效率。但是，若其他人在服务器进行了相关的修改，由于应用软件数据缓存的存在，导致修改的数据不能及时反映到客户端上。从这也可以看出，应用软件的数据缓存跟数据库服务器的高速数据缓存不是一码事。</span></p><p><span style="color: #000000" twffan="done">　　2、语句合法性检查。</span></p><p><span style="color: #000000" twffan="done">　　当在高速缓存中找不到对应的SQL语句时，则数据库服务器进程就会开始检查这条语句的合法性。这里主要是对SQL语句的语法进行检查，看看其是否合乎语法规则。如果服务器进程认为这条SQL语句不符合语法规则的时候，就会把这个错误信息，反馈给客户端。在这个语法检查的过程中，不会对SQL语句中所包含的表名、列名等等进行SQL他只是语法上的检查。</span></p><p><span style="color: #000000" twffan="done">　　3、语言含义检查。</span></p><p><span style="color: #000000" twffan="done">　　若SQL语句符合语法上的定义的话，则服务器进程接下去会对语句中的字段、表等内容进行检查。看看这些字段、表是否在数据库中。如果表名与列名不准确的话，则数据库会就会反馈错误信息给客户端。</span></p><p><span style="color: #000000" twffan="done">　　所以，有时候我们写select语句的时候，若语法与表名或者列名同时写错的话，则系统是先提示说语法错误，等到语法完全正确后，再提示说列名或表名错误。若能够掌握这个顺序的话，则在应用程序排错的时候，可以节省时间。</span></p><p><span style="color: #000000" twffan="done">　　4、获得对象解析锁。</span></p><p><span style="color: #000000" twffan="done">　　当语法、语义都正确后，系统就会对我们需要查询的对象加锁。这主要是为了保障数据的一致性，防止我们在查询的过程中，其他用户对这个对象的结构发生改变。对于加锁的原理与方法，我在其他文章中已经有专门叙述，在这里就略过不谈了。</span></p><p><span style="color: #000000" twffan="done">　　5、数据访问权限的核对。</span></p><p><span style="color: #000000" twffan="done">　　当语法、语义通过检查之后，客户端还不一定能够取得数据。服务器进程还会检查，你所连接的用户是否有这个数据访问的权限。若你连接上服务器的用户不具有数据访问权限的话，则客户端就不能够取得这些数据。故，有时候我们查询数据的时候，辛辛苦苦地把SQL语句写好、编译通过，但是，最后系统返回个&ldquo;没有权限访问数据&rdquo;的错误信息，让我们气半死。这在前端应用软件开发调试的过程中，可能会碰到。所以，要注意这个问题，数据库服务器进程先检查语法与语义，然后才会检查访问权限。</span></p><p><span style="color: #000000" twffan="done">　　6、确定最佳执行计划。</span></p><p><span style="color: #000000" twffan="done">　　当语句与语法都没有问题，权限也匹配的话，服务器进程还是不会直接对数据库文件进行查询。服务器进程会根据一定的规则，对这条语句进行优化。不过要注意，这个优化是有限的。一般在应用软件开发的过程中，需要对数据库的sql语言进行优化，这个优化的作用要大大地大于服务器进程的自我优化。所以，一般在应用软件开发的时候，数据库的优化是少不了的。</span></p><p><span style="color: #000000" twffan="done">　　当服务器进程的优化器确定这条查询语句的最佳执行计划后，就会将这条SQL语句与执行计划保存到数据高速缓存。如此的话，等以后还有这个查询时，就会省略以上的语法、语义与权限检查的步骤，而直接执行SQL语句，提高SQL语句处理效率。</span></p><p><span style="color: #000000" twffan="done"><p><span style="color: #000000" twffan="done"><strong>　第三步：语句执行。</strong></span></p><p><span style="color: #000000" twffan="done">　　语句解析只是对SQL语句的语法进行解析，以确保服务器能够知道这条语句到底表达的是什么意思。等到语句解析完成之后，数据库服务器进程才会真正的执行这条SQL语句。</span></p><p><span style="color: #000000" twffan="done">　　这个语句执行也分两种情况。一是若被选择行所在的数据块已经被读取到数据缓冲区的话，则服务器进程会直接把这个数据传递给客户端，而不是从数据库文件中去查询数据。若数据不在缓冲区中，则服务器进程将从数据库文件中查询相关数据，并把这些数据放入到数据缓冲区中。</span></p><p><span style="color: #000000" twffan="done">　　这里仍然要注意一点，就是Oracle数据库中，定义了很多种类的高速缓存。像上面所说的SQL语句缓存与现在讲的数据缓存。我们在学习数据库的时候，需要对这些缓存有一个清晰的认识，并了解各个种类缓存的作用。这对于我们后续数据库维护与数据库优化是非常有用的。</span></p><p><span style="color: #000000" twffan="done"><strong>　　第四步：提取数据。</strong></span></p><p><span style="color: #000000" twffan="done">　　当语句执行完成之后，查询到的数据还是在服务器进程中，还没有被传送到客户端的用户进程。所以，在服务器端的进程中，有一个专门负责数据提取的一段代码。他的作用就是把查询到的数据结果返回给用户端进程，从而完成整个查询动作。</span></p><p><span style="color: #000000" twffan="done">　　从这整个查询处理过程中，我们在数据库开发或者应用软件开发过程中，<strong>需要注意以下几点：</strong></span></p><p><span style="color: #000000" twffan="done">　　一是要了解数据库缓存跟应用软件缓存是两码事情。数据库缓存只有在数据库服务器端才存在，在客户端是不存在的。只有如此，才能够保证数据库缓存中的内容跟数据库文件的内容一致。才能够根据相关的规则，防止数据脏读、错读的发生。而应用软件所涉及的数据缓存，由于跟数据库缓存不是一码事情，所以，应用软件的数据缓存虽然可以提高数据的查询效率，但是，却打破了数据一致性的要求，有时候会发生脏读、错读等情况的发生。所以，有时候，在应用软件上有专门一个功能，用来在必要的时候清除数据缓存。不过，这个数据缓存的清除，也只是清除本机上的数据缓存，或者说，只是清除这个应用程序的数据缓存，而不会清除数据库的数据缓存。</span></p><p><span style="color: #000000" twffan="done">　　二是绝大部分SQL语句都是按照这个处理过程处理的。我们DBA或者基于Oracle数据库的开发人员了解这些语句的处理过程，对于我们进行涉及到SQL语句的开发与调试，是非常有帮助的。有时候，掌握这些处理原则，可以减少我们排错的时间。特别要注意，数据库是把数据查询权限的审查放在语法语义的后面进行检查的。所以，有时会若光用数据库的权限控制原则，可能还不能满足应用软件权限控制的需要。此时，就需要应用软件的前台设置，实现权限管理的要求。而且，有时应用数据库的权限管理，也有点显得繁琐，会增加服务器处理的工作量。因此，对于记录、字段等的查询权限控制，大部分程序涉及人员喜欢在应用程序中实现，而不是在数据库上实现<strong>。</strong></span></p></span></p>]]></description><category>SQL</category><comments>http://www.chinacmcc.com/post/20.html#comment</comments><wfw:comment>http://www.chinacmcc.com/</wfw:comment><wfw:commentRss>http://www.chinacmcc.com/feed.asp?cmt=20</wfw:commentRss><trackback:ping>http://www.chinacmcc.com/cmd.asp?act=tb&amp;id=20&amp;key=2b9574c4</trackback:ping></item><item><title>[SQL学习]30条经典的SQL语句</title><author>a@b.com (walker)</author><link>http://www.chinacmcc.com/post/19.html</link><pubDate>Tue, 07 Jul 2009 14:19:49 +0800</pubDate><guid>http://www.chinacmcc.com/post/19.html</guid><description><![CDATA[<div><a target="_blank" href="http://shrewdwolf2008.blog.51cto.com/313377/92348">原文地址</a></div><div>&nbsp;</div><div>关于索引，推荐转载的这篇文章<br /><a href="http://blog.csdn.net/dutguoyi/archive/2006/01/10/575617.aspx"><a href="http://blog.csdn.net/dutguoyi/archive/2006/01/10/575617.aspx" target="_blank">http://blog.csdn.net/dutguoyi/archive/2006/01/10/575617.aspx</a></a></div><div>改善SQL语句的效率<br /><a href="http://community.csdn.net/Expert/topic/5087/5087396.xml?temp=.345669"><a href="http://community.csdn.net/Expert/topic/5087/5087396.xml?temp=.345669" target="_blank">http://community.csdn.net/Expert/topic/5087/5087396.xml?temp=.345669</a></a><br />数据量很大怎样加快索检速度<br /><a href="http://community.csdn.net/Expert/topic/5058/5058320.xml?temp=.1229517"><a href="http://community.csdn.net/Expert/topic/5058/5058320.xml?temp=.1229517" target="_blank">http://community.csdn.net/Expert/topic/5058/5058320.xml?temp=.1229517</a></a><br />索引建立方法的区别<br /><a href="http://community.csdn.net/Expert/topic/5068/5068154.xml?temp=.3010218"><a href="http://community.csdn.net/Expert/topic/5068/5068154.xml?temp=.3010218" target="_blank">http://community.csdn.net/Expert/topic/5068/5068154.xml?temp=.3010218</a></a><br />频繁插入删除数据需要更新索引<br /><a href="http://community.csdn.net/Expert/topic/4937/4937910.xml?temp=.8428614"><a href="http://community.csdn.net/Expert/topic/4937/4937910.xml?temp=.8428614" target="_blank">http://community.csdn.net/Expert/topic/4937/4937910.xml?temp=.8428614</a></a><br />测试了一下sql server 2005 全文检索<br /><a href="http://community.csdn.net/Expert/topic/4878/4878430.xml?temp=.6049311"><a href="http://community.csdn.net/Expert/topic/4878/4878430.xml?temp=.6049311" target="_blank">http://community.csdn.net/Expert/topic/4878/4878430.xml?temp=.6049311</a></a></div><div>其他关于效率的高频问题</div><div>判断一个表的数据不在另一个表中最优秀方法？<br /><a href="http://community.csdn.net/Expert/topic/5038/5038742.xml?temp=.4704553"><a href="http://community.csdn.net/Expert/topic/5038/5038742.xml?temp=.4704553" target="_blank">http://community.csdn.net/Expert/topic/5038/5038742.xml?temp=.4704553</a></a><br />删除千万级表中重复记录的办法<br /><a href="http://community.csdn.net/Expert/topic/5089/5089261.xml?temp=.7907068"><a href="http://community.csdn.net/Expert/topic/5089/5089261.xml?temp=.7907068" target="_blank">http://community.csdn.net/Expert/topic/5089/5089261.xml?temp=.7907068</a></a></div><div>数据库数据查询变得不正常类型问题</div><div>大数据量，稳定运行一段时候以后无法得到查询结果。<br /><a href="http://community.csdn.net/Expert/topic/4810/4810464.xml?temp=9.014529E-02"><a href="http://community.csdn.net/Expert/topic/4810/4810464.xml?temp=9.014529E-02" target="_blank">http://community.csdn.net/Expert/topic/4810/4810464.xml?temp=9.014529E-02</a></a></div><div>返回表的字段名称</div><div>select name from syscolumns where id=object_id('jobs')</div><div>select * into b<br />from a where 1&lt;&gt;1</div><div>--刚看到的.新建一个与a表一样的空的b表<br />select * into b<br />from a where 1&lt;&gt;1</div><div>--刚看到的.新建一个与a表一样的空的b表</div><div><br />精点,经典,<br />一些不错的sql语句，自己根据需要收藏吧，分给多点哦:)<br />1、说明：复制表(只复制结构,源表名：a 新表名：b) (Access可用)<br />法一：select * into b from a where 1&lt;&gt;1<br />法二：select top 0 * into b from a</div><div>2、说明：拷贝表(拷贝数据,源表名：a 目标表名：b) (Access可用)<br />insert into b(a, b, c) select d,e,f from b;</div><div>3、说明：跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用)<br />insert into b(a, b, c) select d,e,f from b in &lsquo;具体数据库&rsquo; where 条件<br />例子：..from b in '&quot;&amp;Server.MapPath(&quot;.&quot;)&amp;&quot;\data.mdb&quot; &amp;&quot;' where..</div><div>4、说明：子查询(表名1：a 表名2：b)<br />select a,b,c from a where a IN (select d from b ) 或者: select a,b,c from a where a IN (1,2,3)</div><div>5、说明：显示文章、提交人和最后回复时间<br />select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b</div><div>6、说明：外连接查询(表名1：a 表名2：b)<br />select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c</div><div>7、说明：在线视图查询(表名1：a )<br />select * from (SELECT a,b,c FROM a) T where t.a &gt; 1;</div><div>8、说明：between的用法,between限制查询数据范围时包括了边界值,not between不包括<br />select * from table1 where time between time1 and time2<br />select a,b,c, from table1 where a not between 数值1 and 数值2</div><div>9、说明：in 的使用方法<br />select * from table1 where a [not] in (&lsquo;值1&rsquo;,&rsquo;值2&rsquo;,&rsquo;值4&rsquo;,&rsquo;值6&rsquo;)</div><div>10、说明：两张关联表，删除主表中已经在副表中没有的信息 <br />delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )</div><div>11、说明：四表联查问题：<br />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 .....</div><div>12、说明：日程安排提前五分钟提醒 <br />SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())&gt;5</div><div>13、说明：一条sql 语句搞定数据库分页<br />select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段</div><div>14、说明：前10条记录<br />select top 10 * form table1 where 范围</div><div>15、说明：选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.)<br />select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)</div><div>16、说明：包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表<br />(select a from tableA ) except (select a from tableB) except (select a from tableC)</div><div>17、说明：随机取出10条数据<br />select top 10 * from tablename order by newid()</div><div>18、说明：随机选择记录<br />select newid()</div><div>19、说明：删除重复记录<br />Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)</div><div>20、说明：列出数据库里所有的表名<br />select name from sysobjects where type='U'</div><div>21、说明：列出表里的所有的<br />select name from syscolumns where id=object_id('TableName')</div><div>22、说明：列示type、vender、pcs字段，以type字段排列，case可以方便地实现多重选择，类似select 中的case。<br />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<br />显示结果：<br />type vender pcs<br />电脑 A 1<br />电脑 A 1<br />光盘 B 2<br />光盘 A 2<br />手机 B 3<br />手机 C 3</div><div>23、说明：初始化表table1<br />TRUNCATE TABLE table1</div><div>24、说明：选择从10到15的记录<br />select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc<br />--如何将exec执行结果放入变量中？</div><div>declare @num int, <br />@sqls nvarchar(4000) <br />set @sqls='select @a=count(*) from tableName ' <br />exec sp_executesql @sqls,N'@a int output',@num output <br />select @num</div><div><br />--------------------------------------------------------------------------------</div><div>动态sql语句基本语法 <br />1 :普通SQL语句可以用Exec执行</div><div>eg: Select * from tableName <br />Exec('select * from tableName') <br />Exec sp_executesql N'select * from tableName' -- 请注意字符串前一定要加N</div><div>2:字段名，表名，数据库名之类作为变量时，必须用动态SQL</div><div>eg: <br />declare @fname varchar(20) <br />set @fname = 'FiledName' <br />Select @fname from tableName -- 错误,不会提示错误，但结果为固定值FiledName,并非所要。 <br />Exec('select ' + @fname + ' from tableName') -- 请注意 加号前后的 单引号的边上加空格</div><div>当然将字符串改成变量的形式也可 <br />declare @fname varchar(20) <br />set @fname = 'FiledName' --设置字段名</div><div>declare @s varchar(1000) <br />set @s = 'select ' + @fname + ' from tableName' <br />Exec(@s) -- 成功 <br />exec sp_executesql @s -- 此句会报错</div><div>&nbsp;</div><div>declare @s Nvarchar(1000) -- 注意此处改为nvarchar(1000) <br />set @s = 'select ' + @fname + ' from tableName' <br />Exec(@s) -- 成功 <br />exec sp_executesql @s -- 此句正确</div><div>3. 输出参数 <br />declare @num int, <br />@sqls nvarchar(4000) <br />set @sqls='select count(*) from tableName' <br />exec(@sqls) <br />--如何将exec执行结果放入变量中？</div><div>declare @num int, <br />@sqls nvarchar(4000) <br />set @sqls='select @a=count(*) from tableName ' <br />exec sp_executesql @sqls,N'@a int output',@num output <br />select @num</div><div><br />&nbsp;</div><div>在CSDN上學到了一些<br />1.日期算當月天數:<br />&nbsp;&nbsp;&nbsp; select Day(dateadd(day,-1,convert(datetime,convert(char(07),dateadd(m,1,getdate()),120)+'-01')))<br />&nbsp;&nbsp;&nbsp; select 32-Day(getdate()+(32-Day(getdate())))</div><div>2.簡單的分割字串:<br />&nbsp;&nbsp;&nbsp; 用' union all select 'replace'分割符'</div><div>3....<br />&nbsp;&nbsp;<br />Order By可以指定列序而不用指定列名,在下面的例子里说明它的用处(注意,第三列未指定别名)<br />Select a.ID,a.Name,(Select Count(*) From TableB b Where a.ID=b.PID) From TableA a Order By 3</div><div>--修改用户数据库的排序规则<br />ater database dbname collate SQL_Latin1_General_CP1_CI_AS</div><div><br />--修改字段的排序规则<br />alter table a alter column c2 varchar(50) collate SQL_Latin1_General_CP1_CI_AS</div><div><br />--按姓氏笔画排序<br />select * from 表名 order by 列名 Collate Chinese_PRC_Stroke_ci_as</div><div>&nbsp;</div><div>--按拼音首字母排序<br />select * from 表名 order by 列名 Collate Chinese_PRC_CS_AS_KS_WS</div><div><br />--查找一个Server下含有某个表名的数据库名字<br />EXEC sp_msforeachdb '<br />USE [?]<br />IF OBJECT_ID(N''表名'') IS NOT NULL<br />PRINT N''?'''</div><div><br />--查询所有表名、字段名及字段描述<br />select <br />&nbsp;&nbsp;&nbsp;&nbsp; 表名=object_name(id), <br />&nbsp;&nbsp;&nbsp;&nbsp; 列名=col_name(object_id(object_name(id)),smallid), <br />&nbsp;&nbsp;&nbsp;&nbsp; 描述=value <br />from&nbsp;&nbsp; sysproperties</div><div><br />--查询所有表的记录数明细<br />--方法(1)<br />select&nbsp;&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp; a.name,b.rows&nbsp;&nbsp;<br />from&nbsp;&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp; sysobjects a, sysindexes b<br />where&nbsp;&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp; a.name=b.name and&nbsp;&nbsp; a.type='u' <br />--方法(2)<br />sp_msforeachtable 'select ''?'' as ''表名'',(select sum(1) from ?) as ''记录数'''</div><div><br />--复制表(表结构)<br />--方法(1)<br />select * into Employee_bak from Employee where 1&lt;&gt;1<br />--方法(2)<br />select top 0 * into Employee_bak from Employee<br />--方法(3)<br />--企业管理器中的右键表--&gt;复制,然后在查询分析器中粘贴查看SQL语句</div><div><br />--判断两字符是否完全(区分大小写)相等(如何判断字符的大小写)<br />declare&nbsp;&nbsp; @v&nbsp;&nbsp; nvarchar(10)&nbsp;&nbsp;<br />declare&nbsp;&nbsp; @p&nbsp;&nbsp; nvarchar(10)&nbsp;&nbsp;<br />set&nbsp;&nbsp; @v='NIPSAN'&nbsp;&nbsp;<br />if&nbsp;&nbsp; cast(@v as&nbsp;&nbsp; varbinary)= cast(@p as varbinary)&nbsp;&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp; print N'相等'&nbsp;&nbsp;<br />else&nbsp;&nbsp;&nbsp;&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp; print N'不等'&nbsp;&nbsp;</div><div><br />--得到数据库中所有表的空间/记录情况<br />exec sp_MSForEachTable <br />@precommand=N'<br />create table ##(<br />id int identity,<br />表名 sysname,<br />字段数 int,<br />记录数 int,<br />保留空间 Nvarchar(10),<br />使用空间 varchar(10),<br />索引使用空间 varchar(10),<br />未用空间 varchar(10))',<br />@command1=N'insert ##(表名,记录数,保留空间,使用空间,索引使用空间,未用空间) exec sp_spaceused ''?''</div><div>update ## set 字段数=(select count(*) from syscolumns where id=object_id(''?'')) <br />where id=scope_identity()', @postcommand=N'select * from ## order by id drop table ##'</div><div><br />--查看硬盘分区:<br />EXEC master..xp_fixeddrives</div><div><br />--Order By的一个小技巧<br />/*<br />Order By可以指定列序而不用指定列名,在下面的例子里说明它的用处(注意,第三列未指定别名)<br />Select a.ID,a.Name,(Select Count(*) From TableB b Where a.ID=b.PID) From TableA a Order By 3<br />*/<br />表结构新</div><div>SELECT <br />表名=case when a.colorder=1 then d.name else '' end,<br />表说明=case when a.colorder=1 then isnull(f.value,'') else '' end,<br />字段序号=a.colorder,<br />字段名=a.name,<br />标识=case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '&radic;'else '' end,<br />主键=case when exists(SELECT 1 FROM sysobjects where xtype='PK' and parent_obj=a.id and name in (<br />SELECT name FROM sysindexes WHERE indid in(<br />SELECT indid FROM sysindexkeys WHERE id = a.id AND colid=a.colid<br />))) then '&radic;' else '' end,<br />类型=b.name,<br />占用字节数=a.length,<br />长度=COLUMNPROPERTY(a.id,a.name,'PRECISION'),<br />小数位数=isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0),<br />允许空=case when a.isnullable=1 then '&radic;'else '' end,<br />默认值=isnull(e.text,''),<br />字段说明=isnull(g.[value],''),<br />索引名称=isnull(h.索引名称,''),<br />索引顺序=isnull(h.排序,'')<br />FROM syscolumns a<br />left join systypes b on a.xtype=b.xusertype<br />inner join sysobjects d on a.id=d.id&nbsp;&nbsp; and d.xtype='U' and d.status&gt;=0<br />left join syscomments e on a.cdefault=e.id<br />left join sysproperties g on a.id=g.id and a.colid=g.smallid&nbsp;&nbsp;<br />left join sysproperties f on d.id=f.id and f.smallid=0<br />left join(--这部分是索引信息,如果要显示索引与表及字段的对应关系,可以只要此部分<br />select 索引名称=a.name,c.id,d.colid<br />,排序=case indexkey_property(c.id,b.indid,b.keyno,'isdescending')<br />when 1 then '降序' when 0 then '升序' end<br />from sysindexes a<br />join sysindexkeys b on a.id=b.id and a.indid=b.indid<br />join (--这里的作用是有多个索引时,取索引号最小的那个<br />select id,colid,indid=min(indid) from sysindexkeys<br />group by id,colid) b1 on b.id=b1.id and b.colid=b1.colid and b.indid=b1.indid<br />join sysobjects c on b.id=c.id and c.xtype='U' and c.status&gt;=0<br />join syscolumns d on b.id=d.id and b.colid=d.colid<br />where a.indid not in(0,255)<br />) h on a.id=h.id and a.colid=h.colid<br />--where d.name='要查询的表'&nbsp;&nbsp;&nbsp;&nbsp; --如果只查询指定表,加上此条件<br />order by a.id,a.colorder</div><div>--索引信息</div><div>--索引信息<br />select 索引名称=case when b.keyno=1 then a.name else '' end<br />,表名=case when b.keyno=1 then c.name else '' end<br />,列名=d.name<br />,排序=case indexkey_property(c.id,b.indid,b.keyno,'isdescending')<br />when 1 then '降序' when 0 then '升序' end<br />,聚集=INDEXPROPERTY(c.id,a.name,'IsClustered')<br />,唯一=case INDEXPROPERTY(c.id,a.name,'IsUnique')<br />when 0 then '非唯一'<br />when 1 then case when e.id is null then '唯一索引' else '唯一约束' end<br />end<br />,e.name<br />,填充因子=a.OrigFillFactor<br />from sysindexes a<br />join sysindexkeys b on a.id=b.id and a.indid=b.indid<br />--join (--这里的作用是有多个索引时,取索引号最小的那个<br />--select id,colid,indid=min(indid) from sysindexkeys<br />--group by id,colid) b1 on b.id=b1.id and b.colid=b1.colid and b.indid=b1.indid<br />join sysobjects c on b.id=c.id and c.xtype='U' and c.status&gt;=0<br />join syscolumns d on b.id=d.id and b.colid=d.colid<br />left join sysobjects e on b.indid=e.id and e.xtype='UQ'<br />where a.indid not in(0,255)<br />order by c.name,a.name</div><div>找出表中某一列相同的数据行<br />select *from table where (column in(select column from table group ny column having count(*)&gt;1)</div><div>找出表中某一列相同的数据行<br />select *from table where (column in(select column from table group by column having count(*)&gt;1)</div><div>刚才BY写错拉!<br />--1、查找员工的编号、姓名、部门和出生日期，如果出生日期为空值，<br />--显示日期不详,并按部门排序输出,日期格式为yyyy-mm-dd。<br />select emp_no ,emp_name ,dept ,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; isnull(convert(char(10),birthday,120),'日期不详') birthday<br />from employee<br />order by dept</div><div>--2、查找与喻自强在同一个单位的员工姓名、性别、部门和职称<br />select emp_no,emp_name,dept,title<br />from employee<br />where emp_name&lt;&gt;'喻自强' and dept in<br />&nbsp;&nbsp;&nbsp; (select dept from employee<br />&nbsp;&nbsp;&nbsp;&nbsp; where emp_name='喻自强')</div><div>--3、按部门进行汇总，统计每个部门的总工资<br />select dept,sum(salary)<br />from employee<br />group by dept</div><div>--4、查找商品名称为14寸显示器商品的销售情况，<br />--显示该商品的编号、销售数量、单价和金额<br />select a.prod_id,qty,unit_price,unit_price*qty totprice<br />from sale_item a,product b<br />where a.prod_id=b.prod_id and prod_name='14寸显示器'</div><div>--5、在销售明细表中按产品编号进行汇总，统计每种产品的销售数量和金额<br />select prod_id,sum(qty) totqty,sum(qty*unit_price) totprice<br />from sale_item<br />group by prod_id</div><div>--6、使用convert函数按客户编号统计每个客户1996年的订单总金额<br />select cust_id,sum(tot_amt) totprice<br />from sales<br />where convert(char(4),order_date,120)='1996'<br />group by cust_id</div><div>--7、查找有销售记录的客户编号、名称和订单总额<br />select a.cust_id,cust_name,sum(tot_amt) totprice<br />from customer a,sales b<br />where a.cust_id=b.cust_id<br />group by a.cust_id,cust_name</div><div>--8、查找在1997年中有销售记录的客户编号、名称和订单总额<br />select a.cust_id,cust_name,sum(tot_amt) totprice<br />from customer a,sales b<br />where a.cust_id=b.cust_id and convert(char(4),order_date,120)='1997'<br />group by a.cust_id,cust_name</div><div>--9、查找一次销售最大的销售记录<br />select order_no,cust_id,sale_id,tot_amt<br />from sales<br />where tot_amt=<br />&nbsp;&nbsp;&nbsp; (select max(tot_amt)<br />&nbsp;&nbsp;&nbsp;&nbsp; from sales)</div><div>--10、查找至少有3次销售的业务员名单和销售日期<br />select emp_name,order_date<br />from employee a,sales b <br />where emp_no=sale_id and a.emp_no in<br />&nbsp;&nbsp; (select sale_id<br />&nbsp;&nbsp;&nbsp; from sales<br />&nbsp;&nbsp;&nbsp; group by sale_id<br />&nbsp;&nbsp;&nbsp; having count(*)&gt;=3)<br />order by emp_name</div><div>--11、用存在量词查找没有订货记录的客户名称<br />select cust_name<br />from customer a<br />where not exists<br />&nbsp;&nbsp;&nbsp; (select *<br />&nbsp;&nbsp;&nbsp;&nbsp; from sales b<br />&nbsp;&nbsp;&nbsp;&nbsp; where a.cust_id=b.cust_id)</div><div>--12、使用左外连接查找每个客户的客户编号、名称、订货日期、订单金额<br />--订货日期不要显示时间，日期格式为yyyy-mm-dd<br />--按客户编号排序，同一客户再按订单降序排序输出<br />select a.cust_id,cust_name,convert(char(10),order_date,120),tot_amt<br />from customer a left outer join sales b on a.cust_id=b.cust_id<br />order by a.cust_id,tot_amt desc</div><div>--13、查找16M DRAM的销售情况，要求显示相应的销售员的姓名、<br />--性别，销售日期、销售数量和金额，其中性别用男、女表示<br />select emp_name 姓名, 性别= case a.sex&nbsp;&nbsp; when 'm' then '男'<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; when 'f' then '女' <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else '未'<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; end,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 销售日期= isnull(convert(char(10),c.order_date,120),'日期不详'),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; qty 数量, qty*unit_price as 金额<br />from employee a, sales b, sale_item c,product d<br />where d.prod_name='16M DRAM' and d.pro_id=c.prod_id and<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; a.emp_no=b.sale_id and b.order_no=c.order_no</div><div>--14、查找每个人的销售记录，要求显示销售员的编号、姓名、性别、<br />--产品名称、数量、单价、金额和销售日期<br />select emp_no 编号,emp_name 姓名, 性别= case a.sex when 'm' then '男'<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; when 'f' then '女' <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else '未'<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; end,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; prod_name 产品名称,销售日期= isnull(convert(char(10),c.order_date,120),'日期不详'),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; qty 数量, qty*unit_price as 金额<br />from employee a left outer join sales b on a.emp_no=b.sale_id , sale_item c,product d<br />where d.pro_id=c.prod_id and b.order_no=c.order_no</div><div>--15、查找销售金额最大的客户名称和总货款<br />select cust_name,d.cust_sum<br />from&nbsp;&nbsp;&nbsp; customer a,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (select cust_id,cust_sum<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; from (select cust_id, sum(tot_amt) as cust_sum<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; from sales<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; group by cust_id ) b<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; where b.cust_sum = <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ( select max(cust_sum)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; from (select cust_id, sum(tot_amt) as cust_sum<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; from sales<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; group by cust_id ) c )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ) d<br />where a.cust_id=d.cust_id</div><div>--16、查找销售总额少于1000元的销售员编号、姓名和销售额<br />select emp_no,emp_name,d.sale_sum<br />from&nbsp;&nbsp;&nbsp; employee a,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (select sale_id,sale_sum<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; from (select sale_id, sum(tot_amt) as sale_sum<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; from sales<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; group by sale_id ) b<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; where b.sale_sum &lt;1000&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ) d<br />where a.emp_no=d.sale_id</div><div>--17、查找至少销售了3种商品的客户编号、客户名称、商品编号、商品名称、数量和金额<br />select a.cust_id,cust_name,b.prod_id,prod_name,d.qty,d.qty*d.unit_price<br />from customer a, product b, sales c, sale_item d<br />where a.cust_id=c.cust_id and d.prod_id=b.prod_id and <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; c.order_no=d.order_no and a.cust_id in (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; select cust_id<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; from&nbsp;&nbsp; (select cust_id,count(distinct prod_id) prodid<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; from (select cust_id,prod_id<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; from sales e,sale_item f<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; where e.order_no=f.order_no) g<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; group by cust_id<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; having count(distinct prod_id)&gt;=3) h )</div><div>--18、查找至少与世界技术开发公司销售相同的客户编号、名称和商品编号、商品名称、数量和金额<br />select a.cust_id,cust_name,d.prod_id,prod_name,qty,qty*unit_price<br />from customer a, product b, sales c, sale_item d<br />where a.cust_id=c.cust_id and d.prod_id=b.prod_id and <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; c.order_no=d.order_no&nbsp;&nbsp; and not exists<br />&nbsp;&nbsp; (select f.*<br />&nbsp;&nbsp;&nbsp; from customer x ,sales e, sale_item f<br />&nbsp;&nbsp;&nbsp; where cust_name='世界技术开发公司' and x.cust_id=e.cust_id and<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; e.order_no=f.order_no and not exists<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ( select g.*<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; from sale_item g, sales&nbsp;&nbsp; h<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; where g.prod_id = f.prod_id and g.order_no=h.order_no and<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; h.cust_id=a.cust_id)<br />&nbsp;&nbsp;&nbsp;&nbsp; )<br />&nbsp;&nbsp;&nbsp;<br />19、查找表中所有姓刘的职工的工号，部门，薪水<br />select emp_no,emp_name,dept,salary<br />from employee<br />where emp_name like '刘%'</div><div>20、查找所有定单金额高于20000的所有客户编号<br />select cust_id<br />from sales<br />where tot_amt&gt;20000</div><div>21、统计表中员工的薪水在40000-60000之间的人数<br />select count(*)as 人数<br />from employee<br />where salary between 40000 and 60000</div><div>22、查询表中的同一部门的职工的平均工资，但只查询＂住址＂是＂上海市＂的员工<br />select avg(salary) avg_sal,dept <br />from employee <br />where addr like '上海市%'<br />group by dept</div><div>23、将表中住址为&quot;上海市&quot;的员工住址改为&quot;北京市&quot;<br />update employee&nbsp;&nbsp;<br />set addr like '北京市'<br />where addr like '上海市'</div><div>24、查找业务部或会计部的女员工的基本信息。<br />select emp_no,emp_name,dept<br />from employee <br />where sex='F'and dept in ('业务','会计')</div><div>25、显示每种产品的销售金额总和，并依销售金额由大到小输出。<br />select prod_id ,sum(qty*unit_price)<br />from sale_item <br />group by prod_id<br />order by sum(qty*unit_price) desc<br />26、选取编号界于&lsquo;C0001&rsquo;和&lsquo;C0004&rsquo;的客户编号、客户名称、客户地址。<br />select CUST_ID,cust_name,addr<br />from customer <br />where cust_id between 'C0001' AND 'C0004'</div><div>27、计算出一共销售了几种产品。<br />select count(distinct prod_id) as '共销售产品数'<br />from sale_item</div><div>28、将业务部员工的薪水上调3%。<br />update employee<br />set salary=salary*1.03<br />where dept='业务'<br />&nbsp;&nbsp;&nbsp;&nbsp;<br />29、由employee表中查找出薪水最低的员工信息。<br />select *<br />from employee<br />where salary=<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (select min(salary )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; from employee )</div><div>30、使用join查询客户姓名为&quot;客户丙&quot;所购货物的&quot;客户名称&quot;,&quot;定单金额&quot;,&quot;定货日期&quot;,&quot;电话号码&quot;<br />select a.cust_id,b.tot_amt,b.order_date,a.tel_no<br />from customer a join sales b<br />on a.cust_id=b.cust_id and cust_name like '客户丙'</div><div>31、由sales表中查找出订单金额大于&ldquo;E0013业务员在1996/10/15这天所接每一张订单的金额&rdquo;的所有订单。<br />select *<br />from sales<br />where tot_amt&gt;all<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (select tot_amt <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; from sales <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; where sale_id='E0013'and order_date='1996/10/15')<br />order by tot_amt</div><div>32、计算'P0001'产品的平均销售单价<br />select avg(unit_price)<br />from sale_item<br />where prod_id='P0001'</div><div>33、找出公司女员工所接的定单<br />select sale_id,tot_amt<br />from sales<br />where sale_id in <br />(select sale_id from employee<br />where sex='F')</div><div>34、找出同一天进入公司服务的员工<br />select a.emp_no,a.emp_name,a.date_hired<br />from employee a<br />join employee b<br />on (a.emp_no!=b.emp_no and a.date_hired=b.date_hired)<br />order by a.date_hired</div><div>35、找出目前业绩超过232000元的员工编号和姓名。<br />select emp_no,emp_name<br />from employee <br />where emp_no in<br />(select sale_id<br />from sales <br />group by sale_id<br />having sum(tot_amt)&lt;232000)</div><p>&nbsp;</p>]]></description><category>SQL</category><comments>http://www.chinacmcc.com/post/19.html#comment</comments><wfw:comment>http://www.chinacmcc.com/</wfw:comment><wfw:commentRss>http://www.chinacmcc.com/feed.asp?cmt=19</wfw:commentRss><trackback:ping>http://www.chinacmcc.com/cmd.asp?act=tb&amp;id=19&amp;key=fc5735f8</trackback:ping></item><item><title>[SQL学习]从SQL语言的分类谈COMMIT和ROLLBACK的用法</title><author>a@b.com (walker)</author><link>http://www.chinacmcc.com/post/18.html</link><pubDate>Tue, 07 Jul 2009 09:06:31 +0800</pubDate><guid>http://www.chinacmcc.com/post/18.html</guid><description><![CDATA[<p><a target="_blank" href="http://www.blogjava.net/realsmy/archive/2007/04/23/113026.html">原文地址</a></p><p>从功能上划分，SQL语言可以分为DDL,DML和DCL三大类。</p><p>&nbsp;&nbsp;&nbsp; 1. DDL（Data Definition Language） <br />&nbsp;&nbsp;&nbsp; 数据定义语言，用于定义和管理 SQL 数据库中的所有对象的语言 ；<br />&nbsp;&nbsp;&nbsp; CREATE---创建表<br />&nbsp;&nbsp;&nbsp; ALTER---修改表<br />&nbsp;&nbsp;&nbsp; DROP---删除表</p><p>&nbsp;&nbsp;&nbsp; 2. DML（Data Manipulation Language） <br />&nbsp;&nbsp;&nbsp; 数据操纵语言，SQL中处理数据等操作统称为数据操纵语言 ； <br />&nbsp;&nbsp;&nbsp; INSERT---数据的插入<br />&nbsp;&nbsp;&nbsp; DELETE---数据的删除<br />&nbsp;&nbsp;&nbsp; UPDATE---数据的修改<br />&nbsp;&nbsp;&nbsp; SELECT---数据的查询</p><p>&nbsp;&nbsp;&nbsp; DCL（Data Control Language） <br />&nbsp;&nbsp;&nbsp; 数据控制语言，用来授予或回收访问数据库的某种特权，并控制数据库操纵事务发生的时间及效果，对数据库实行监视等；<br />&nbsp;&nbsp;&nbsp; GRANT---授权。<br />&nbsp;&nbsp;&nbsp; ROLLBACK---回滚<br />&nbsp;&nbsp;&nbsp; COMMIT---提交。</p><p>&nbsp;&nbsp;&nbsp;&nbsp; 提交数据有三种类型：显式提交、隐式提交及自动提交。下面分别说明这三种类型。</p><p>&nbsp;&nbsp;&nbsp; (1) 显式提交</p><p>&nbsp;&nbsp;&nbsp; 用COMMIT命令直接完成的提交为显式提交。</p><p>&nbsp;&nbsp;&nbsp; (2) 隐式提交</p><p>&nbsp;&nbsp;&nbsp; 用SQL命令间接完成的提交为隐式提交。这些命令是：</p><p>&nbsp;&nbsp;&nbsp; ALTER，AUDIT，COMMENT，CONNECT，CREATE，DISCONNECT，DROP，</p><p>EXIT，GRANT，NOAUDIT，QUIT，REVOKE，RENAME。</p><p>&nbsp;&nbsp;&nbsp; (3) 自动提交</p><p>&nbsp;&nbsp;&nbsp; 若把AUTOCOMMIT设置为ON，则在插入、修改、删除语句执行后，</p><p>系统将自动进行提交，这就是自动提交。其格式为： SQL&gt;SET AUTOCOMMIT ON；</p><p>&nbsp;&nbsp;&nbsp; COMMIT / ROLLBACK这两个命令用的时候要小心。 COMMIT / ROLLBACK 都是用在执行 DML语句（INSERT / DELETE / UPDATE / SELECT ）之后的。DML 语句，执行完之后，处理的数据，都会放在回滚段中（除了 SELECT 语句），等待用户进行提交（COMMIT）或者回滚 （ROLLBACK），当用户执行 COMMIT / ROLLBACK后，放在回滚段中的数据就会被删除。</p><p>&nbsp;&nbsp;&nbsp; （SELECT 语句执行后，数据都存在共享池。提供给其他人查询相同的数据时，直接在共享池中提取，不用再去数据库中提取，提高了数据查询的速度。）</p><p>&nbsp;&nbsp;&nbsp; 所有的 DML 语句都是要显式提交的，也就是说要在执行完DML语句之后，执行 COMMIT 。而其他的诸如 DDL 语句的，都是隐式提交的。也就是说，在运行那些非 DML 语句后，数据库已经进行了隐式提交，例如 CREATE TABLE，在运行脚本后，表已经建好了，并不在需要你再进行显式提交。</p>]]></description><category>SQL</category><comments>http://www.chinacmcc.com/post/18.html#comment</comments><wfw:comment>http://www.chinacmcc.com/</wfw:comment><wfw:commentRss>http://www.chinacmcc.com/feed.asp?cmt=18</wfw:commentRss><trackback:ping>http://www.chinacmcc.com/cmd.asp?act=tb&amp;id=18&amp;key=0f4c1a84</trackback:ping></item><item><title>[SQL学习]Oracle 插入时间时 报错：ORA-01861: 文字与格式字符串不匹配 的解决办法 </title><author>a@b.com (walker)</author><link>http://www.chinacmcc.com/post/17.html</link><pubDate>Fri, 03 Jul 2009 14:44:06 +0800</pubDate><guid>http://www.chinacmcc.com/post/17.html</guid><description><![CDATA[<p><a target="_blank" href="http://www.cnblogs.com/raymond19840709/archive/2007/08/15/856104.html">原文链接</a></p><p>往oracle中插入时间&nbsp; '2007-12-28 10:07:24'<br /><br />如果直接按照字符串方式，或者，直接使用to_date('2007-12-28 10:07:24'）,没有指定日期格式，就会报错：ORA-01861: 文字与格式字符串不匹配<br /><br />必须指定日期格式 <br /><br />to_date('2007-12-28 10:07:24' , 'yyyy-mm-dd hh24:mi:ss')</p><p>&nbsp;</p>]]></description><category>SQL</category><comments>http://www.chinacmcc.com/post/17.html#comment</comments><wfw:comment>http://www.chinacmcc.com/</wfw:comment><wfw:commentRss>http://www.chinacmcc.com/feed.asp?cmt=17</wfw:commentRss><trackback:ping>http://www.chinacmcc.com/cmd.asp?act=tb&amp;id=17&amp;key=bf34802a</trackback:ping></item><item><title>[SQL学习]Char 和 Varchar 的比较</title><author>a@b.com (walker)</author><link>http://www.chinacmcc.com/post/16.html</link><pubDate>Fri, 03 Jul 2009 10:49:32 +0800</pubDate><guid>http://www.chinacmcc.com/post/16.html</guid><description><![CDATA[<p>最近因为工作原因经常用到oracle和SQL，因之前从未接触过，目前正在努力学习中，不懂的东东基本上从网上找来然后在此存档</p><p>来源：中国自学编程网&nbsp;</p><p>&nbsp;&nbsp; 据考证：在字符长度一定时CHAR的性能比VARCHAR好，而在长度不确定时，CHAR类型的字段在使用时性能略差。这个在sqlServer数据库下面能够体现，并且这个字段是经常使用的。 <br />区别：&nbsp; <br />&nbsp;&nbsp; 1．CHAR的长度是固 定的，而VARCHAR2的长度是可以变化的， 比如，存储字符串&ldquo;abc\&quot;，对于CHAR (20)，表示你存储的字符将占20个字节(包括17个空字符)，而同样的VARCHAR2 (20)则只占用3个字节的长度，20只是最大值，当你存储的字符小于20时，按实际长度存储。由于char是以固定长度的，所以它的速度会比 varchar快得多!但程序处理起来要麻烦一点，要用trim之类的函数把两边的空格去掉!&nbsp;&nbsp; <br />&nbsp;&nbsp; 2．CHAR的效率比VARCHAR2的效率稍高。&nbsp; <br />&nbsp;&nbsp; 3．目前VARCHAR是VARCHAR2的同义词。工业标准的VARCHAR类型可以存储空字符串，但是oracle不这样做，尽管它保留以后这样做的权利。Oracle自己开发了一个数据类型VARCHAR2，这个类型不是一个标准的VARCHAR，它将在数据库中varchar列可以存储空字符串的特性改为存储NULL值。如果你想有向后兼容的能力，Oracle建议使用VARCHAR2而不是VARCHAR。&nbsp; <br />&nbsp; <br />&nbsp;&nbsp; 何时该用CHAR，何时该用varchar2？&nbsp; <br />&nbsp;&nbsp; CHAR与VARCHAR2是一对矛盾的统一体，两者是互补的关系.&nbsp; <br />&nbsp;&nbsp;&nbsp; VARCHAR2比CHAR节省空间，在效率上比CHAR会稍微差一些，即要想获得效率，就必须牺牲一定的空间，这也就是我们在数据库设计上常说的&lsquo;以空间换效率&rsquo;。&nbsp; <br />&nbsp;&nbsp;&nbsp; VARCHAR2 虽然比CHAR节省空间，但是如果一个VARCHAR2列经常被修改，而且每次被修改的数据的长度不同，这会引起&lsquo;行迁移&rsquo;(Row Migration)现象，而这造成多余的I/O，是数据库设计和调整中要尽力避免的，在这种情况下用CHAR代替VARCHAR2会更好一些。</p>]]></description><category>SQL</category><comments>http://www.chinacmcc.com/post/16.html#comment</comments><wfw:comment>http://www.chinacmcc.com/</wfw:comment><wfw:commentRss>http://www.chinacmcc.com/feed.asp?cmt=16</wfw:commentRss><trackback:ping>http://www.chinacmcc.com/cmd.asp?act=tb&amp;id=16&amp;key=bcaccdae</trackback:ping></item></channel></rss>
