ÓÃSQL Server 2005 CTE¼ò»¯²éѯ
SQL Server 2005Òý½øÁËÒ»¸öºÜÓмÛÖµµÄеÄTransact-SQLÓïÑÔ×é¼þ£ºÒ»¸öͨÓñí±í´ïʽ£¨Common Table Expression£¬CTE£©£¬ËüÊÇÅÉÉú±íºÍÊÓͼµÄÒ»¸ö±ã½ÝµÄÌæ´ú¡£Í¨¹ýʹÓÃCTE£¬ÎÒÃÇ¿ÉÒÔ´´½¨Ò»¸öÃüÃû½á¹û¼¯À´ÔÚSELECT¡¢INSERT¡¢UPDATEºÍDELETEÓï¾äÖÐÒýÓ㬶øÎÞÐë±£´æ½á¹û¼¯½á¹¹µÄÈκÎÔªÊý¾Ý¡£ÔÚ±¾ÎÄÖУ¬ÎÒ½«²ûÊöÈçºÎÔÚSQL Server 2005Öд´½¨CTE——°üÀ¨ÈçºÎʹÓÃCTEÀ´´´½¨Ò»¸öµÝ¹é²éѯ——²¢¾Ù¼¸¸öÀý×ÓÀ´ËµÃ÷ËüÃÇÊÇÈçºÎʹÓõġ£×¢Ò⣬±¾ÎÄÖÐËùÓÐÀý×Ó¶¼Ê¹ÓÃSQL Server 2005µÄAdventureWorksʾÀýÊý¾Ý¿â¡£
ÔÚSQL Server 2005Öд´½¨Ò»¸ö»ù±¾CTE
ÎÒÃÇ¿ÉÒÔÔÚSELECT¡¢INSERT¡¢UPDATE»òDELETEÓï¾ä֮ǰÌí¼ÓÒ»¸öWITH×Ó¾äÀ´¹¹³ÉÒ»¸öCTE¡£ÏÂÃæµÄÓï·¨ÏÔʾÁËWITH×Ó¾äµÄ»ù±¾¹¹ÔìºÍCTE¶¨Ò壺
[WITH <CTE_definition> [£¬...n]]
<SELECT£¬ INSERT£¬ UPDATE£¬ or DELETE statement that
calls the CTEs>
<CTE_definition>::=
CTE_name [(column_name [£¬...n ])]
AS
(
CTE_query
)
ÈçÉÏÃæÓï¾äËùʾ£¬Äã¿ÉÒÔÔÚ¿ÉÑ¡µÄWITH×Ó¾äÖж¨Òå¶à¸öCTE¡£CTE¶¨Òå°üº¬CTEÃû³Æ¡¢CTE×Ö¶ÎÃû³Æ¡¢AS¹Ø¼ü×ÖºÍÀ¨ºÅÖеÄCTE²éѯ¡£×¢Ò⣬CTE×Ö¶ÎÃû³ÆµÄÊýÄ¿±ØÐëÓëCTE²éѯ·µ»ØµÄ×Ö¶ÎÊýÄ¿ÏàÆ¥Åä¡£ÁíÍ⣬Èç¹ûCTE²éѯÌṩËùÓÐ×Ö¶ÎÃû³Æ£¬ÄÇô×Ö¶ÎÃû³ÆÊÇ¿ÉÑ¡µÄ¡£
ÏÖÔÚÎÒÃÇÒѾ¶ÔSQL ServerµÄCTEÓï·¨ÓÐÁË»ù±¾µÄÁ˽⣬ÏÂÃæÈÃÎÒÃÇÀ´¿´Ò»¸öCTE¶¨ÒåµÄÀý×Ó£¬ÒÔ±ã¸üºÃµØÀí½âÕâ¸öÓï·¨¡£ÏÂÃæµÄÀý×Ó¶¨ÒåÁËÒ»¸öÃüÃûΪProductSold µÄCTE£¬½Ó×ÅÔÚSELECTÓï¾äÖÐÒýÓÃÁËCTE£º
WITH ProductSold (ProductID£¬ TotalSold)
AS
(
SELECT ProductID£¬ SUM(OrderQty)
from Sales.SalesOrderDetail
GROUP BY ProductID
)
SELECT p.ProductID£¬ p.Name£¬ p.ProductNumber£¬
ps.TotalSold
from Production.Product AS p
INNER JOIN ProductSold AS ps
ON p.ProductID = ps.ProductID
ÕâÀï¿ÉÒÔ¿´µ½£¬WITH×Ó¾äÔÚÒýÓÃCTEµÄSELECTÓï¾ä֮ǰ¡£WITH×Ó¾äµÄµÚÒ»Ðаüº¬ÁËCTEµÄÃû³Æ£¨ProductSold£©ÒÔ¼°ÔÚCTE µÄÁ½¸ö×Ö¶ÎÃû³Æ(ProductID ºÍTotalSold)¡£½Ó×ÅÊÇAS¹Ø¼ü×Ö£¬½ô½Ó×ÅÊÇÀ¨ºÅÖеÄCTE²éѯ¡£ÕâÑù£¬CTE²éѯ·µ»ØÁËÿ¸ö²úÆ·µÄÏúÊÛ×ÜÊý¡£
Ïà¹ØÎĵµ£º
2009-11-18 12:51:46
ÏÞ¶¨´¦Àí¼Ç¼µÄµ¥Î»£¬rowcount=100±íʽÿ´Î´¦Àí100ÌõÊý¾Ý¡£Êµ¼Ê´¦ÀíµÄ¼Ç¼ÊýÓÉrowcountºÍwhere×Ó¾ä¾ö¶¨¡£Èç¹û·ûºÏwhereµÄ¼Ç¼Êý´óÓÚrowcount,ÔòÓÐrowcount¾ö¶¨£¬Èç¹ûСÓÚrowcount£¬ÔòÓÉwhere¾ö¶¨¡£
create table tb(id int identity(1,1),num int)
insert into tb
values(1)
while @@ ......
[C#]
public void RunSqlTransaction(string myConnString)
{
SqlConnection myConnection = new SqlConnection(myConnString);
myConnection.Open();
SqlCommand myCommand = myConnection.CreateCommand();
SqlTransaction m ......
declare @i int
set @i=1
while @i<30
begin
insert into test (userid) values(@i)
set @i=@i+1
end
---------------
while Ìõ¼þ
begin
Ö´ÐвÙ×÷
set @i=@i+1
end
WHILE
ÉèÖÃÖظ´Ö´ÐÐ SQL Óï¾ä»òÓï¾ä¿éµÄÌõ¼þ¡£Ö»ÒªÖ¸¶¨µÄÌõ¼þΪÕ棬¾ÍÖظ´Ö´ÐÐÓï¾ä¡£¿ÉÒÔʹÓà BREAK ºÍ CONTINUE ¹Ø¼ü×ÖÔÚÑ»·ÄÚ²¿¿ ......
ÀýÈç²éÕÒ¹ØÓÚ¶Ôlibrary ....µÈ´ýʼþÓй±Ï×µÄSQL
select sql_text from V$sqlarea where (address,hash_value) in
(select sql_address,sql_hash_value from v$session where event like 'library%');
´ËÓï¾äÖ»ÄÜÔËÐÐÓÚ10g°æ±¾ÒÔÉÏ£¬ÒòΪ10gÖÐv$sessionÊÓͼ°üº¬Á˵ȴýʼþµÄÐÅÏ¢ÁË£¬9iÖÐûÓÐ ......