SQL ÖÐWith as µÄÓ÷¨
Ò»£®WITH ASµÄº¬Òå
WITH AS¶ÌÓҲ½Ð×ö×Ó²éѯ²¿·Ö£¨subquery factoring£©£¬¿ÉÒÔÈÃÄã×öºÜ¶àÊÂÇ飬¶¨ÒåÒ»¸öSQLƬ¶Ï£¬¸ÃSQLƬ¶Ï»á±»Õû¸öSQLÓï¾äËùÓõ½¡£ÓеÄʱºò£¬ÊÇΪÁËÈÃSQLÓï¾äµÄ¿É¶ÁÐÔ¸ü¸ßЩ£¬Ò²ÓпÉÄÜÊÇÔÚUNION ALLµÄ²»Í¬²¿·Ö£¬×÷ΪÌṩÊý¾ÝµÄ²¿·Ö¡£
Ìرð¶ÔÓÚUNION ALL±È½ÏÓÐÓá£ÒòΪUNION ALLµÄÿ¸ö²¿·Ö¿ÉÄÜÏàͬ£¬µ«ÊÇÈç¹ûÿ¸ö²¿·Ö¶¼È¥Ö´ÐÐÒ»±éµÄ»°£¬Ôò³É±¾Ì«¸ß£¬ËùÒÔ¿ÉÒÔʹÓÃWITH AS¶ÌÓÔòÖ»ÒªÖ´ÐÐÒ»±é¼´¿É¡£Èç¹ûWITH AS¶ÌÓïËù¶¨ÒåµÄ±íÃû±»µ÷ÓÃÁ½´ÎÒÔÉÏ£¬ÔòÓÅ»¯Æ÷»á×Ô¶¯½«WITH AS¶ÌÓïËù»ñÈ¡µÄÊý¾Ý·ÅÈëÒ»¸öTEMP±íÀÈç¹ûÖ»ÊDZ»µ÷ÓÃÒ»´Î£¬Ôò²»»á¡£¶øÌáʾmaterializeÔòÊÇÇ¿Öƽ«WITH AS¶ÌÓïÀïµÄÊý¾Ý·ÅÈëÒ»¸öÈ«¾ÖÁÙʱ±íÀï¡£ºÜ¶à²éѯͨ¹ýÕâÖÖ·½·¨¶¼¿ÉÒÔÌá¸ßËٶȡ£
¶þ£®Ê¹Ó÷½·¨
ÏÈ¿´ÏÂÃæÒ»¸öǶÌ׵IJéѯÓï¾ä£º
select * from person.StateProvince where CountryRegionCode in
(select CountryRegionCode from person.CountryRegion where Name like 'C%')
ÉÏÃæµÄ²éѯÓï¾äʹÓÃÁËÒ»¸ö×Ó²éѯ¡£ËäÈ»ÕâÌõSQLÓï¾ä²¢²»¸´ÔÓ£¬µ«Èç¹ûǶÌ׵IJã´Î¹ý¶à£¬»áʹSQLÓï¾ä·Ç³£ÄÑÒÔÔĶÁºÍά»¤¡£Òò´Ë£¬Ò²¿ÉÒÔʹÓñí±äÁ¿µÄ·½Ê½À´½â¾öÕâ¸öÎÊÌ⣬SQLÓï¾äÈçÏ£º
declare @t table(CountryRegionCode nvarchar(3))
insert into @t(CountryRegionCode) (select CountryRegionCode from person.CountryRegion where Name like 'C%')
select * from person.StateProvince where CountryRegionCode
in (select * from @t)
ËäÈ»ÉÏÃæµÄSQLÓï¾äÒª±ÈµÚÒ»ÖÖ·½Ê½¸ü¸´ÔÓ£¬µ«È´½«×Ó²éѯ·ÅÔÚÁ˱í±äÁ¿@tÖУ¬ÕâÑù×ö½«Ê¹SQLÓï¾ä¸üÈÝÒ×ά»¤£¬µ«ÓÖ»á´øÀ´ÁíÒ»¸öÎÊÌ⣬¾ÍÊÇÐÔÄܵÄËðʧ¡£ÓÉÓÚ±í±äÁ¿Êµ¼ÊÉÏʹÓÃÁËÁÙʱ±í£¬´Ó¶øÔö¼ÓÁ˶îÍâµÄI/O¿ªÏú£¬Òò´Ë£¬±í±äÁ¿µÄ·½Ê½²¢²»Ì«ÊʺÏÊý¾ÝÁ¿´óÇÒƵ·±²éѯµÄÇé¿ö¡£Îª´Ë£¬ÔÚSQL Server 2005ÖÐÌṩÁËÁíÍâÒ»ÖÖ½â¾ö·½°¸£¬Õâ¾ÍÊǹ«Óñí±í´ïʽ£¨CTE£©£¬Ê¹ÓÃCTE£¬¿ÉÒÔʹSQLÓï¾äµÄ¿Éά»¤ÐÔ£¬Í¬Ê±£¬CTEÒª±È±í±äÁ¿µÄЧÂʸߵöࡣ
ÏÂÃæÊÇCTEµÄÓï·¨£º
[ WITH <common_table_expression> [ ,n ] ]
<common_table_expression>::=
expression_name [ ( column_name [ ,n ] ) ]
AS
( CTE_query_definition )
ÏÖÔÚʹÓÃCTEÀ´½â¾öÉÏÃæµÄÎÊÌ⣬SQLÓï¾äÈçÏ£º
with
cr as
(
select CountryRegionCode from person.CountryRegion where Name like 'C%'
)
select * from person.StateProvince where CountryRegionCode in (select * from c
Ïà¹ØÎĵµ£º
»ù±¾µÄSql±àдעÒâÊÂÏî
¾¡Á¿ÉÙÓÃIN²Ù×÷·û£¬»ù±¾ÉÏËùÓеÄIN²Ù×÷·û¶¼¿ÉÒÔÓÃEXISTS´úÌæ¡£
²»ÓÃNOT IN²Ù×÷·û£¬¿ÉÒÔÓÃNOT EXISTS»òÕßÍâÁ¬½Ó+Ìæ´ú¡£
OracleÔÚÖ´ÐÐIN×Ó²éѯʱ£¬Ê×ÏÈÖ´ÐÐ×Ó²éѯ£¬½«²éѯ½á¹û·ÅÈëÁÙʱ±íÔÙÖ´ÐÐÖ÷²éѯ¡£¶øEXISTÔòÊÇÊ×Ïȼì²éÖ÷²éѯ£¬È»ºóÔËÐÐ×Ó²éѯֱµ½ÕÒµ½
µÚÒ»¸öÆ¥ÅäÏî¡£NOT EXISTS±ÈNOT INЧÂÊÉ ......
1:replace º¯Êý
µÚÒ»¸ö²ÎÊýÄãµÄ×Ö·û´®£¬µÚ¶þ¸ö²ÎÊýÄãÏëÌæ»»µÄ²¿·Ö£¬µÚÈý¸ö²ÎÊýÄãÒªÌæ»»³Éʲô
select replace('lihan','a','b')
-----------------------------
lihbn
£¨ËùÓ°ÏìµÄÐÐÊýΪ 1 ÐУ©
============================================== ......
--Óï ¾ä ¹¦ ÄÜ
--Êý¾Ý²Ù×÷
SELECT --´ÓÊý¾Ý¿â±íÖмìË÷Êý¾ÝÐкÍÁÐ
INSERT --ÏòÊý¾Ý¿â±íÌí¼ÓÐÂÊý¾ÝÐÐ
DELETE --´ÓÊý¾Ý¿â±íÖÐɾ³ýÊý¾ÝÐÐ
UPDATE --¸üÐÂÊý¾Ý¿â±íÖеÄÊý¾Ý
--Êý¾Ý¶¨Òå
CREATE TABLE --´´½¨Ò»¸öÊý¾Ý¿â±í
DROP TABLE --´ÓÊý¾Ý¿âÖÐɾ³ý±í
......
Case¾ßÓÐÁ½ÖÖ¸ñʽ¡£¼òµ¥Caseº¯ÊýºÍCaseËÑË÷º¯Êý¡£
--¼òµ¥Caseº¯Êý
CASE sex
WHEN '1' THEN 'ÄÐ'
WHEN '2' THEN 'Å®'
ELSE 'ÆäËû' END
--CaseËÑË÷º¯Êý
CASE WHEN sex = '1' THEN 'ÄÐ'
  ......