Ò׽ؽØͼÈí¼þ¡¢µ¥Îļþ¡¢Ãâ°²×°¡¢´¿ÂÌÉ«¡¢½ö160KB

ÓÃ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²éѯ·µ»ØÁËÿ¸ö²úÆ·µÄÏúÊÛ×ÜÊý¡£


Ïà¹ØÎĵµ£º

SQL Server ÖÐ int¡¢bigint¡¢smallint ºÍtinyint

ʹÓÃÕûÊýÊý¾ÝµÄ¾«È·Êý×ÖÊý¾ÝÀàÐÍ¡£
 bigint ´Ó -2^63 (-9223372036854775808) µ½ 2^63-1 (9223372036854775807) µÄÕûÐÍÊý¾Ý£¨ËùÓÐÊý×Ö£©¡£
              ´æ´¢´óСΪ 8 ¸ö×Ö½Ú¡£
 int ´Ó -2^31 (-2,147,483,648) µ½ 2^31 - 1 (2,147,483,64 ......

¹ØÓÚsqlÖÐʱ¼äµÄ¸ñʽת»»


sql server2000ÖÐʹÓÃconvertÀ´È¡µÃdatetimeÊý¾ÝÀàÐÍÑùʽ£¨È«£©
ÈÕÆÚÊý¾Ý¸ñʽµÄ´¦Àí£¬Á½¸öʾÀý£º
CONVERT(varchar(16), ʱ¼äÒ», 20) ½á¹û£º2007-02-01 08:02/*ʱ¼äÒ»°ãΪgetdate()º¯Êý»òÊý¾Ý±íÀïµÄ×Ö¶Î*/
CONVERT(varchar(10), ʱ¼äÒ», 23) ½á¹û£º2007-02-01 /*varchar(10)±íʾÈÕÆÚÊä³öµÄ¸ñʽ£¬Èç¹û²»¹»³¤»á·¢Éú½ØÈ¡*/ ......

C# Ö´ÐÐSQLÊÂÎñʵÀý´úÂë

 [C#]
public void RunSqlTransaction(string myConnString)
{
    SqlConnection myConnection = new SqlConnection(myConnString);
    myConnection.Open();
    SqlCommand myCommand = myConnection.CreateCommand();
    SqlTransaction m ......

ÔÚSQL ServerÓ¦ÓÃÖÐʹÓÃOUTPUT×Ó¾ä

 ÏÖÔÚ´ó¶àÊýÃèÊöSQL Server 2005ÐÂÌØÐÔµÄÎÄÕ¶¼¹Ø×¢ÓÚ»ª¶ø²»ÊµµÄÌØÐÔ£¬ÈçSQLCLR»òXMLÊý¾ÝÀàÐÍ£¬¶ø¶ÔÐí¶àºÜºÃµÄÀϵÄT-SQLÓïÑԵĸĽøûÓеõ½Ó¦ÓеĹØ×¢¡£ÎÒÔø¾­´ÓÐí¶àDBA¿ÚÖÐÌýµ½ÁîËûÃǸüÐ˷ܵÄÊÇ¿´µ½T-SQLÓïÑԵĸĽø,¶ø²»ÊÇÄÇЩгöÏֺͷ¢²¼µÄ¹¦ÄÜ¡£¶ÔÓÚSQLÓïÑÔµÄÒ»¸öºÜÓÐÓõÄʵ¼Ê¸Ä½øÊÇOUTPUT×Ӿ䣬ËüÔÊÐí²éѯһ¸öÊý¾ ......
© 2009 ej38.com All Rights Reserved. ¹ØÓÚE½¡ÍøÁªÏµÎÒÃÇ | Õ¾µãµØͼ | ¸ÓICP±¸09004571ºÅ