<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>select &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/select/</link>
	<description>Feed of posts on WordPress.com tagged "select"</description>
	<pubDate>Thu, 26 Nov 2009 05:32:57 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[SELECT]]></title>
<link>http://thewaterrat.com/2009/11/25/select-18/</link>
<pubDate>Wed, 25 Nov 2009 22:52:24 +0000</pubDate>
<dc:creator>Andrea Favale</dc:creator>
<guid>http://thewaterrat.com/2009/11/25/select-18/</guid>
<description><![CDATA[Live music comes to iTunes Yahoo Boss loses Vik Singh Saab faces scrapheap as sale fails Worse than ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://theappleblog.com/2009/11/25/live-music-comes-to-itunes/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+OmMalik+%28GigaOM%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;"><strong>Live music</strong> comes to iTunes</span></a><br />
<a href="http://www.techcrunch.com/2009/11/25/yahoo-boss-loses-vik-singh/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+Techcrunch+%28TechCrunch%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;">Yahoo Boss loses <strong>Vik Singh</strong></span></a><br />
<a href="http://online.wsj.com/article/SB10001424052748704779704574555703312066522.html" target="_blank"><span style="color:#b22222;"><strong>Saab</strong> faces scrapheap as sale fails</span></a><br />
<a href="http://www.forbes.com/2009/11/25/nbc-universal-comcast-business-entertainment-nbc-comcast.html?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+typepad%2Falleyinsider%2Fsilicon_alley_insider+%28Silicon+Alley+Insider%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;">Worse than the <strong>NBC-Comcast</strong> deal? No deal</span></a><br />
<a href="http://newteevee.com/2009/11/25/italian-prosecutors-said-to-be-seeking-jail-time-for-google-execs/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+typepad%2Falleyinsider%2Fsilicon_alley_insider+%28Silicon+Alley+Insider%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;"><strong>Italian prosecutors</strong> said to be seeking jail time for Google execs</span></a></p>
<p><a href="http://thewaterrat.wordpress.com/files/2009/11/albertone.jpg"><img class="alignleft size-medium wp-image-702" title="albertone" src="http://thewaterrat.wordpress.com/files/2009/11/albertone.jpg?w=254" alt="" width="254" height="300" /></a></p>
<p>&#160;</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Collecting Antique Watches - Hobby For A Select Few]]></title>
<link>http://uiuimymy.wordpress.com/2009/11/25/collecting-antique-watches-hobby-for-a-select-few/</link>
<pubDate>Wed, 25 Nov 2009 17:06:20 +0000</pubDate>
<dc:creator>jaydcaswell1234</dc:creator>
<guid>http://uiuimymy.wordpress.com/2009/11/25/collecting-antique-watches-hobby-for-a-select-few/</guid>
<description><![CDATA[Antique watches generally refer to mechanical watches that were made more than fifty years ago or mo]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Antique watches generally refer to mechanical watches that were made more than fifty years ago or more. Antique watches are not very useful in keeping accurate track of time, and instead make good gifts or a nice piece of decoration.</p>
<p>The antique watch business is a multi-billion dollar business. However there are a lot of fakes out there so buying an antique watch requires careful research.</p>
<p>A Brief History of Time</p>
<p>Some knowledge of mechanical watches will help a lot in judging the approximate date of manufacture of the antique watch:</p>
<p>1500s Peter Henlein of Germany created the first pocket watch</p>
<p>1660s Christian Huygens invented the remontoire</p>
<p>1680s Repeating mechanism for bells and sounds patented</p>
<p>1700s Rubies used in watch movements</p>
<p>1750s Enamel used on watch dials</p>
<p>1760s Lever escapement invented</p>
<p>1800s First self winding watch invented</p>
<p>1840s First watch to have winding and setting through crown</p>
<p>1914  World War I popularizes the wristwatch</p>
<p>1914  First wristwatch with alarm</p>
<p>1926  First water proof wristwatch</p>
<p>1956  First watch to display day and date</p>
<p>1960  First watch to have scratch-proof dial</p>
<p>Sources of Antique Watch</p>
<p>Antique watches of many established companies are available such as Rolex, Omega, Universal Geneve, Angelus, Vacheron &#38; Constantin, Seiko, Benrus, Breitling, Gruen, Zodiac, IWC, Movado, <b>TAG</b> <b>Heuer</b>, Hamilton, Ingersoll, Shakosha (Citizen watch company of Japan) Gallet, Wittnauer, Bulova etc. There are a lot of sources on the internet selling watches online. Good buys can be found at auctions and second hand markets but the authenticity of these antique watches are doubtful.</p>
<p>Maintenance of Antique Watch</p>
<p>Maintenance of an antique watch is very difficult. The parts are not easily available and antique watches cannot be repaired at all watch shops. So do make sure that the seller also guarantees their repair if the need arises. Most antique watch sellers also provide maintenance and care manuals for the antique watch. Be sure to follow the instructions.</p>
<p>Cost of Antique Watch</p>
<p>Antique watches are available anywhere between $300 to millions of dollars depending upon the make, the date of manufacture, the history of the watch and the jewels in the antique watch. The market price of the antique watch is determined by its snob appeal and social acceptance.</p>
<p>Antique watches make wonderful gifts and give the wearer a distinct and artistic look. Antique watches combine artistic appeal and nostalgic charm. However, antique watches are costly in general and need a lot of maintenance and care.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[SELECT]]></title>
<link>http://thewaterrat.com/2009/11/24/select-17/</link>
<pubDate>Tue, 24 Nov 2009 23:30:49 +0000</pubDate>
<dc:creator>Andrea Favale</dc:creator>
<guid>http://thewaterrat.com/2009/11/24/select-17/</guid>
<description><![CDATA[Google needs to start rewarding its customers YC-funded WakeMate helps you kiss groggy mornings good]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://www.entrepreneurcountry.net/articles/expert-view-julie-meyer/237-google-needs-to-start-rewarding-its-customers" target="_blank"><span style="color:#b22222;"><strong>Google</strong> needs to start rewarding its customers</span></a><br />
<a href="http://www.techcrunch.com/2009/11/24/wakemate-sleep-aid/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+Techcrunch+%28TechCrunch%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;">YC-funded <strong>WakeMate</strong> helps you kiss groggy mornings goodbye</span></a><br />
<a href="http://www.pehub.com/56595/mgm-sends-out-ndas/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+pehub%2Fnews%2Fall+%28PEHub+News%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;"><strong>MGM</strong> sends out NDAs</span></a><br />
<a href="http://www.techcrunch.com/2009/11/23/flightcaster-flight-delay/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+Techcrunch+%28TechCrunch%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;"><strong>FlightCaster</strong> takes off with $1.3 million in funding and a new API</span></a><br />
<a href="http://gigaom.com/2009/11/24/asana/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+OmMalik+%28GigaOM%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;"><strong>Former Facebookers</strong> get $9m for workforce telepathy</span></a></p>
<p><a href="http://thewaterrat.wordpress.com/files/2009/11/telepathy.jpg"><img class="alignleft size-full wp-image-676" title="telepathy" src="http://thewaterrat.wordpress.com/files/2009/11/telepathy.jpg" alt="" width="180" height="214" /></a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Blackwater's Secret War in Pakistan ]]></title>
<link>http://rogerhollander.wordpress.com/2009/11/24/blackwaters-secret-war-in-pakistan/</link>
<pubDate>Tue, 24 Nov 2009 20:34:14 +0000</pubDate>
<dc:creator>rogerhollander</dc:creator>
<guid>http://rogerhollander.wordpress.com/2009/11/24/blackwaters-secret-war-in-pakistan/</guid>
<description><![CDATA[Jeremy Scahill The Nation, November 23, 2009 At a covert forward operating base run by the US Joint ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Jeremy Scahill</p>
<p>The Nation, November 23, 2009</p>
<p>At a covert forward operating base run by the US Joint Special Operations Command (JSOC) in the Pakistani port city of Karachi, members of an elite division of Blackwater are at the center of a secret program in which they plan targeted assassinations of suspected Taliban and Al Qaeda operatives, &#8220;snatch and grabs&#8221; of high-value targets and other sensitive action inside and outside Pakistan, an investigation by <em>The Nation</em> has found. The Blackwater operatives also assist in gathering intelligence and help direct a secret US military drone bombing campaign that runs parallel to the well-documented CIA predator strikes, according to a well-placed source within the US military intelligence apparatus.</p>
<p>The source, who has worked on covert US military programs for years, including in Afghanistan and Pakistan, has direct knowledge of Blackwater&#8217;s involvement. He spoke to <em>The Nation</em> on condition of anonymity because the program is classified. The source said that the program is so &#8220;compartmentalized&#8221; that senior figures within the Obama administration and the US military chain of command may not be aware of its existence.</p>
<p>The White House did not return calls or email messages seeking comment for this story. Capt. John Kirby, the spokesperson for Adm. Michael Mullen, Chair of the Joint Chiefs of Staff, told <em>The Nation</em>, &#8220;We do not discuss current operations one way or the other, regardless of their nature.&#8221; A defense official, on background, specifically denied that Blackwater performs work on drone strikes or intelligence for JSOC in Pakistan. &#8220;We don&#8217;t have any contracts to do that work for us. We don&#8217;t contract that kind of work out, period,&#8221; the official said. &#8220;There has not been, and is not now, contracts between JSOC and that organization for these types of services.&#8221;</p>
<p>The previously unreported program, the military intelligence source said, is distinct from the CIA assassination program that the agency&#8217;s director, Leon Panetta, announced he had canceled in June 2009. &#8220;This is a parallel operation to the CIA,&#8221; said the source. &#8220;They are two separate beasts.&#8221; The program puts Blackwater at the epicenter of a US military operation within the borders of a nation against which the United States has not declared war&#8211;knowledge that could further strain the already tense relations between the United States and Pakistan. In 2006, the United States and Pakistan struck a deal that authorized JSOC to enter Pakistan to hunt Osama bin Laden with the understanding that Pakistan would deny it had given permission. Officially, the United States is not supposed to have any active military operations in the country.</p>
<p>Blackwater, which recently changed its name to Xe Services and US Training Center, denies the company is operating in Pakistan. &#8220;Xe Services has only one employee in Pakistan performing construction oversight for the U.S. Government,&#8221; Blackwater spokesperson Mark Corallo said in a statement to <em>The Nation</em>, adding that the company has &#8220;no other operations of any kind in Pakistan.&#8221;</p>
<p>A former senior executive at Blackwater confirmed the military intelligence source&#8217;s claim that the company is working in Pakistan for the CIA and JSOC, the premier counterterrorism and covert operations force within the military. He said that Blackwater is also working for the Pakistani government on a subcontract with an Islamabad-based security firm that puts US Blackwater operatives on the ground with Pakistani forces in counter-terrorism operations, including house raids and border interdictions, in the North-West Frontier Province and elsewhere in Pakistan. This arrangement, the former executive said, allows the Pakistani government to utilize former US Special Operations forces who now work for Blackwater while denying an official US military presence in the country. He also confirmed that Blackwater has a facility in Karachi and has personnel deployed elsewhere in Pakistan. The former executive spoke on condition of anonymity.</p>
<p>His account and that of the military intelligence source were borne out by a US military source who has knowledge of Special Forces actions in Pakistan and Afghanistan. When asked about Blackwater&#8217;s covert work for JSOC in Pakistan, this source, who also asked for anonymity, told <em>The Nation</em>, &#8220;From my information that I have, that is absolutely correct,&#8221; adding, &#8220;There&#8217;s no question that&#8217;s occurring.&#8221;</p>
<p>&#8220;It wouldn&#8217;t surprise me because we&#8217;ve outsourced nearly everything,&#8221; said Col. Lawrence Wilkerson, who served as Secretary of State Colin Powell&#8217;s chief of staff from 2002 to 2005, when told of Blackwater&#8217;s role in Pakistan. Wilkerson said that during his time in the Bush administration, he saw the beginnings of Blackwater&#8217;s involvement with the sensitive operations of the military and CIA. &#8220;Part of this, of course, is an attempt to get around the constraints the Congress has placed on DoD. If you don&#8217;t have sufficient soldiers to do it, you hire civilians to do it. I mean, it&#8217;s that simple. It would not surprise me.&#8221;</p>
<p><strong>The Counterterrorism Tag Team in Karachi</strong></p>
<p>The covert JSOC program with Blackwater in Pakistan dates back to at least 2007, according to the military intelligence source. The current head of JSOC is Vice Adm. William McRaven, who took over the post from Gen. Stanley McChrystal, who headed JSOC from 2003 to 2008 before being named the top US commander in Afghanistan.  Blackwater&#8217;s presence in Pakistan is &#8220;not really visible, and that&#8217;s why nobody has cracked down on it,&#8221; said the source. Blackwater&#8217;s operations in Pakistan, he said, are not done through State Department contracts or publicly identified Defense contracts. &#8220;It&#8217;s Blackwater via JSOC, and it&#8217;s a classified no-bid [contract] approved on a rolling basis.&#8221; The main JSOC/Blackwater facility in Karachi, according to the source, is nondescript: three trailers with various generators, satellite phones and computer systems are used as a makeshift operations center. &#8220;It&#8217;s a very rudimentary operation,&#8221; says the source. &#8220;I would compare it to [CIA] outposts in Kurdistan or any of the Special Forces outposts. It&#8217;s very bare bones, and that&#8217;s the point.&#8221;</p>
<p>Blackwater&#8217;s work for JSOC in Karachi is coordinated out of a Task Force based at Bagram Air Base in neighboring Afghanistan, according to the military intelligence source. While JSOC technically runs the operations in Karachi, he said, it is largely staffed by former US special operations soldiers working for a division of Blackwater, once known as Blackwater SELECT, and intelligence analysts working for a Blackwater affiliate, Total Intelligence Solutions (TIS), which is owned by Blackwater&#8217;s founder, Erik Prince. The military source said that the name Blackwater SELECT may have been changed recently. Total Intelligence, which is run out of an office on the ninth floor of a building in the Ballston area of Arlington, Virginia, is staffed by former analysts and operatives from the CIA, DIA, FBI and other agencies. It is modeled after the CIA&#8217;s counterterrorism center. In Karachi, TIS runs a &#8220;media-scouring/open-source network,&#8221; according to the source. Until recently, Total Intelligence was run by two former top CIA officials, Cofer Black and Robert Richer, both of whom have left the company. In Pakistan, Blackwater is not using either its original name or its new moniker, Xe Services, according to the former Blackwater executive. &#8220;They are running most of their work through TIS because the other two [names] have such a stain on them,&#8221; he said. Corallo, the Blackwater spokesperson, denied that TIS or any other division or affiliate of Blackwater has any personnel in Pakistan.</p>
<p>The US military intelligence source said that Blackwater&#8217;s classified contracts keep getting renewed at the request of JSOC. Blackwater, he said, is already so deeply entrenched that it has become a staple of the US military operations in Pakistan. According to the former Blackwater executive, &#8220;The politics that go with the brand of BW is somewhat set aside because what you&#8217;re doing is really one military guy to another.&#8221; Blackwater&#8217;s first known contract with the CIA for operations in Afghanistan was awarded in 2002 and was for work along the Afghanistan-Pakistan border.</p>
<p>One of the concerns raised by the military intelligence source is that some Blackwater personnel are being given rolling security clearances above their approved clearances. Using Alternative Compartmentalized Control Measures (ACCMs), he said, the Blackwater personnel are granted clearance to a Special Access Program, the bureaucratic term used to describe highly classified &#8220;black&#8221; operations. &#8220;With an ACCM, the security manager can grant access to you to be exposed to and operate within compartmentalized programs far above &#8217;secret&#8217;&#8211;even though you have no business doing so,&#8221; said the source. It allows Blackwater personnel that &#8220;do not have the requisite security clearance or do not hold a security clearance whatsoever to participate in classified operations by virtue of trust,&#8221; he added. &#8220;Think of it as an ultra-exclusive level above top secret. That&#8217;s exactly what it is: a circle of love.&#8221; Blackwater, therefore, has access to &#8220;all source&#8221; reports that are culled in part from JSOC units in the field. &#8220;That&#8217;s how a lot of things over the years have been conducted with contractors,&#8221; said the source. &#8220;We have contractors that regularly see things that top policy-makers don&#8217;t unless they ask.&#8221;</p>
<p>According to the source, Blackwater has effectively marketed itself as a company whose operatives have &#8220;conducted lethal direct action missions and now, for a price, you can have your own planning cell. JSOC just ate that up,&#8221; he said, adding, &#8220;They have a sizable force in Pakistan&#8211;not for any nefarious purpose if you really want to look at it that way&#8211;but to support a legitimate contract that&#8217;s classified for JSOC.&#8221; Blackwater&#8217;s Pakistan JSOC contracts are secret and are therefore shielded from public oversight, he said. The source is not sure when the arrangement with JSOC began, but he says that a spin-off of Blackwater SELECT &#8220;was issued a no-bid contract for support to shooters for a JSOC Task Force and they kept extending it.&#8221; Some of the Blackwater personnel, he said, work undercover as aid workers. &#8220;Nobody even gives them a second thought.&#8221;</p>
<p>The military intelligence source said that the Blackwater/JSOC Karachi operation is referred to as &#8220;Qatar cubed,&#8221; in reference to the US forward operating base in Qatar that served as the hub for the planning and implementation of the US invasion of Iraq. &#8220;This is supposed to be the brave new world,&#8221; he says. &#8220;This is the Jamestown of the new millennium and it&#8217;s meant to be a lily pad. You can jump off to Uzbekistan, you can jump back over the border, you can jump sideways, you can jump northwest. It&#8217;s strategically located so that they can get their people wherever they have to without having to wrangle with the military chain of command in Afghanistan, which is convoluted. They don&#8217;t have to deal with that because they&#8217;re operating under a classified mandate.&#8221;</p>
<p>In addition to planning drone strikes and operations against suspected Al Qaeda and Taliban forces in Pakistan for both JSOC and the CIA, the Blackwater team in Karachi also helps plan missions for JSOC inside Uzbekistan against the Islamic Movement of Uzbekistan, according to the military intelligence source. Blackwater does not actually carry out the operations, he said, which are executed on the ground by JSOC forces. &#8220;That piqued my curiosity and really worries me because I don&#8217;t know if you noticed but I was never told we are at war with Uzbekistan,&#8221; he said. &#8220;So, did I miss something, did Rumsfeld come back into power?&#8221;</p>
<p><strong>Pakistan&#8217;s Military Contracting Maze</strong></p>
<p>Blackwater, according to the military intelligence source, is not doing the actual killing as part of its work in Pakistan. &#8220;The SELECT personnel are not going into places with private aircraft and going after targets,&#8221; he said. &#8220;It&#8217;s not like Blackwater SELECT people are running around assassinating people.&#8221; Instead, US Special Forces teams carry out the plans developed in part by Blackwater. The military intelligence source drew a distinction between the Blackwater operatives who work for the State Department, which he calls &#8220;Blackwater Vanilla,&#8221; and the seasoned Special Forces veterans who work on the JSOC program. &#8220;Good or bad, there&#8217;s a small number of people who know how to pull off an operation like that. That&#8217;s probably a good thing,&#8221; said the source. &#8220;It&#8217;s the Blackwater SELECT people that have and continue to plan these types of operations because they&#8217;re the only people that know how and they went where the money was. It&#8217;s not trigger-happy fucks, like some of the PSD [Personal Security Detail] guys. These are not people that believe that Barack Obama is a socialist, these are not people that kill innocent civilians. They&#8217;re very good at what they do.&#8221;</p>
<p>The former Blackwater executive, when asked for confirmation that Blackwater forces were not actively killing people in Pakistan, said, &#8220;that&#8217;s not entirely accurate.&#8221; While he concurred with the military intelligence source&#8217;s description of the JSOC and CIA programs, he pointed to another role Blackwater is allegedly playing in Pakistan, not for the US government but for Islamabad. According to the executive, Blackwater works on a subcontract for Kestral Logistics, a powerful Pakistani firm, which specializes in military logistical support, private security and intelligence consulting. It is staffed with former high-ranking Pakistani army and government officials. While Kestral&#8217;s main offices are in Pakistan, it also has branches in several other countries.</p>
<p>A spokesperson for the US State Department&#8217;s Directorate of Defense Trade Controls (DDTC), which is responsible for issuing licenses to US corporations to provide defense-related services to foreign governments or entities, would neither confirm nor deny for <em>The Nation</em> that Blackwater has a license to work in Pakistan or to work with Kestral. &#8220;We cannot help you,&#8221; said department spokesperson David McKeeby after checking with the relevant DDTC officials. &#8220;You&#8217;ll have to contact the companies directly.&#8221; Blackwater&#8217;s Corallo said the company has &#8220;no operations of any kind&#8221; in Pakistan other than the one employee working for the DoD. Kestral did not respond to inquiries from <em>The Nation</em>.</p>
<p>According to federal lobbying records, Kestral recently hired former Assistant Secretary of State for Western Hemisphere Affairs Roger Noriega, who served in that post from 2003 to 2005, to lobby the US government, including the State Department, USAID and Congress, on foreign affairs issues &#8220;regarding [Kestral's] capabilities to carry out activities of interest to the United States.&#8221; Noriega was hired through his firm, Vision Americas, which he runs with Christina Rocca, a former CIA operations official who served as assistant secretary of state for South Asian affairs from 2001 to 2006 and was deeply involved in shaping US policy toward Pakistan. In October 2009, Kestral paid Vision Americas $15,000 and paid a Vision Americas-affiliated firm, Firecreek Ltd., an equal amount to lobby on defense and foreign policy issues.</p>
<p>For years, Kestral has done a robust business in defense logistics with the Pakistani government and other nations, as well as top US defense companies. Blackwater owner Erik Prince is close with Kestral CEO Liaquat Ali Baig, according to the former Blackwater executive. &#8220;Ali and Erik have a pretty close relationship,&#8221; he said. &#8220;They&#8217;ve met many times and struck a deal, and they [offer] mutual support for one another.&#8221; Working with Kestral, he said, Blackwater has provided convoy security for Defense Department shipments destined for Afghanistan that would arrive in the port at Karachi. Blackwater, according to the former executive, would guard the supplies as they were transported overland from Karachi to Peshawar and then west through the Torkham border crossing, the most important supply route for the US military in Afghanistan.</p>
<p>According to the former executive, Blackwater operatives also integrate with Kestral&#8217;s forces in sensitive counterterrorism operations in the North-West Frontier Province, where they work in conjunction with the Pakistani Interior Ministry&#8217;s paramilitary force, known as the Frontier Corps (alternately referred to as &#8220;frontier scouts&#8221;). The Blackwater personnel are technically advisers, but the former executive said that the line often gets blurred in the field. Blackwater &#8220;is providing the actual guidance on how to do [counterterrorism operations] and Kestral&#8217;s folks are carrying a lot of them out, but they&#8217;re having the guidance and the overwatch from some BW guys that will actually go out with the teams when they&#8217;re executing the job,&#8221; he said. &#8220;You can see how that can lead to other things in the border areas.&#8221; He said that when Blackwater personnel are out with the Pakistani teams, sometimes its men engage in operations against suspected terrorists. &#8220;You&#8217;ve got BW guys that are assisting&#8230; and they&#8217;re all going to want to go on the jobs&#8211;so they&#8217;re going to go with them,&#8221; he said. &#8220;So, the things that you&#8217;re seeing in the news about how this Pakistani military group came in and raided this house or did this or did that&#8211;in some of those cases, you&#8217;re going to have Western folks that are right there at the house, if not in the house.&#8221; Blackwater, he said, is paid by the Pakistani government through Kestral for consulting services. &#8220;That gives the Pakistani government the cover to say, &#8216;Hey, no, we don&#8217;t have any Westerners doing this. It&#8217;s all local and our people are doing it.&#8217; But it gets them the expertise that Westerners provide for [counterterrorism]-related work.&#8221;</p>
<p>The military intelligence source confirmed Blackwater works with the Frontier Corps, saying, &#8220;There&#8217;s no real oversight. It&#8217;s not really on people&#8217;s radar screen.&#8221;</p>
<p>In October, in response to Pakistani news reports that a Kestral warehouse in Islamabad was being used to store heavy weapons for Blackwater, the US Embassy in Pakistan released a statement denying the weapons were being used by &#8220;a private American security contractor.&#8221; The statement said, &#8220;Kestral Logistics is a private logistics company that handles the importation of equipment and supplies provided by the United States to the Government of Pakistan. All of the equipment and supplies were imported at the request of the Government of Pakistan, which also certified the shipments.&#8221;</p>
<p><strong>Who is Behind the Drone Attacks?</strong></p>
<p>Since President Barack Obama was inaugurated, the United States has expanded drone bombing raids in Pakistan. Obama first ordered a drone strike against targets in North and South Waziristan on January 23, and the strikes have been conducted consistently ever since. The Obama administration has now surpassed the number of Bush-era strikes in Pakistan and has faced fierce criticism from Pakistan and some US lawmakers over civilian deaths. A drone attack in June killed as many as sixty people attending a Taliban funeral.</p>
<p>In August, the <em>New York Times</em> reported that Blackwater works for the CIA at &#8220;hidden bases in Pakistan and Afghanistan, where the company&#8217;s contractors assemble and load Hellfire missiles and 500-pound laser-guided bombs on remotely piloted Predator aircraft.&#8221; In February, The <em>Times</em> of London obtained a satellite image of a secret CIA airbase in Shamsi, in Pakistan&#8217;s southwestern province of Baluchistan, showing three drone aircraft. The <em>New York Times</em> also reported that the agency uses a secret base in Jalalabad, Afghanistan, to strike in Pakistan.</p>
<p>The military intelligence source says that the drone strike that reportedly killed Pakistani Taliban leader Baitullah Mehsud, his wife and his bodyguards in Waziristan in August was a CIA strike, but that many others attributed in media reports to the CIA are actually JSOC strikes. &#8220;Some of these strikes are attributed to OGA [Other Government Agency, intelligence parlance for the CIA], but in reality it&#8217;s JSOC and their parallel program of UAVs [unmanned aerial vehicles] because they also have access to UAVs. So when you see some of these hits, especially the ones with high civilian casualties, those are almost always JSOC strikes.&#8221; The Pentagon has stated bluntly, &#8220;There are no US military strike operations being conducted in Pakistan.&#8221;</p>
<p>The military intelligence source also confirmed that Blackwater continues to work for the CIA on its drone bombing program in Pakistan, as previously reported in the <em>New York Times</em>, but added that Blackwater is working on JSOC&#8217;s drone bombings as well. &#8220;It&#8217;s Blackwater running the program for both CIA and JSOC,&#8221; said the source. When civilians are killed, &#8220;people go, &#8216;Oh, it&#8217;s the CIA doing crazy shit again unchecked.&#8217; Well, at least 50 percent of the time, that&#8217;s JSOC [hitting] somebody they&#8217;ve identified through HUMINT [human intelligence] or they&#8217;ve culled the intelligence themselves or it&#8217;s been shared with them and they take that person out and that&#8217;s how it works.&#8221;</p>
<p>The military intelligence source says that the CIA operations are subject to Congressional oversight, unlike the parallel JSOC bombings. &#8220;Targeted killings are not the most popular thing in town right now and the CIA knows that,&#8221; he says. &#8220;Contractors and especially JSOC personnel working under a classified mandate are not [overseen by Congress], so they just don&#8217;t care. If there&#8217;s one person they&#8217;re going after and there&#8217;s thirty-four people in the building, thirty-five people are going to die. That&#8217;s the mentality.&#8221; He added, &#8220;They&#8217;re not accountable to anybody and they know that. It&#8217;s an open secret, but what are you going to do, shut down JSOC?&#8221;</p>
<p>In addition to working on covert action planning and drone strikes, Blackwater SELECT also provides private guards to perform the sensitive task of security for secret US drone bases, JSOC camps and Defense Intelligence Agency camps inside Pakistan, according to the military intelligence source.</p>
<p>Mosharraf Zaidi, a well-known Pakistani journalist who has served as a consultant for the UN and European Union in Pakistan and Afghanistan, says that the Blackwater/JSOC program raises serious questions about the norms of international relations. &#8220;The immediate question is, How do you define the active pursuit of military objectives in a country with which not only have you not declared war but that is supposedly a front-line non-NATO ally in the US struggle to contain extremist violence coming out of Afghanistan and the border regions of Afghanistan and Pakistan?&#8221; asks Zaidi, who is currently a columnist for <em>The News</em>, the biggest English-language daily in Pakistan. &#8220;Let&#8217;s forget Blackwater for a second. What this is confirming is that there are US military operations in Pakistan that aren&#8217;t about logistics or getting food to Bagram; that are actually about the exercise of physical violence, physical force inside of Pakistani territory.&#8221;</p>
<p><strong>JSOC: Rumsfeld and Cheney&#8217;s Extra Special Force</strong></p>
<p>Colonel Wilkerson said that he is concerned that with General McChrystal&#8217;s elevation as the military commander of the Afghan war&#8211;which is increasingly seeping into Pakistan&#8211;there is a concomitant rise in JSOC&#8217;s power and influence within the military structure. &#8220;I don&#8217;t see how you can escape that; it&#8217;s just a matter of the way the authority flows and the power flows, and it&#8217;s inevitable, I think,&#8221; Wilkerson told <em>The Nation</em>. He added, &#8220;I&#8217;m alarmed when I see execute orders and combat orders that go out saying that the supporting force is Central Command and the supported force is Special Operations Command,&#8221; under which JSOC operates. &#8220;That&#8217;s backward. But that&#8217;s essentially what we have today.&#8221;</p>
<p>From 2003 to 2008 McChrystal headed JSOC, which is headquartered at Pope Air Force Base and Fort Bragg in North Carolina, where Blackwater&#8217;s 7,000-acre operating base is also situated. JSOC controls the Army&#8217;s Delta Force, the Navy&#8217;s SEAL Team 6, as well as the Army&#8217;s 75th Ranger Regiment and 160th Special Operations Aviation Regiment, and the Air Force&#8217;s 24th Special Tactics Squadron. JSOC performs strike operations, reconnaissance in denied areas and special intelligence missions. Blackwater, which was founded by former Navy SEALs, employs scores of veteran Special Forces operators&#8211;which several former military officials pointed to as the basis for Blackwater&#8217;s alleged contracts with JSOC.</p>
<p>Since 9/11, many top-level Special Forces veterans have taken up employment with private firms, where they can make more money doing the highly specialized work they did in uniform. &#8220;The Blackwater individuals have the experience. A lot of these individuals are retired military, and they&#8217;ve been around twenty to thirty years and have experience that the younger Green Beret guys don&#8217;t,&#8221; said retired Army Lieut. Col. Jeffrey Addicott, a well-connected military lawyer who served as senior legal counsel for US Army Special Forces. &#8220;They&#8217;re known entities. Everybody knows who they are, what their capabilities are, and they&#8217;ve got the experience. They&#8217;re very valuable.&#8221;</p>
<p>&#8220;They make much more money being the smarts of these operations, planning hits in various countries and basing it off their experience in Chechnya, Bosnia, Somalia, Ethiopia,&#8221; said the military intelligence source. &#8220;They were there for all of these things, they know what the hell they&#8217;re talking about. And JSOC has unfortunately lost the institutional capability to plan within, so they hire back people that used to work for them and had already planned and executed these [types of] operations. They hired back people that jumped over to Blackwater SELECT and then pay them exorbitant amounts of money to plan future operations. It&#8217;s a ridiculous revolving door.&#8221;</p>
<p>While JSOC has long played a central role in US counterterrorism and covert operations, military and civilian officials who worked at the Defense and State Departments during the Bush administration described in interviews with <em>The Nation</em> an extremely cozy relationship that developed between the executive branch (primarily through Vice President Dick Cheney and Defense Secretary Donald Rumsfeld) and JSOC. During the Bush era, Special Forces turned into a virtual stand-alone operation that acted outside the military chain of command and in direct coordination with the White House. Throughout the Bush years, it was largely General McChrystal who ran JSOC. &#8220;What I was seeing was the development of what I would later see in Iraq and Afghanistan, where Special Operations forces would operate in both theaters without the conventional commander even knowing what they were doing,&#8221; said Colonel Wilkerson. &#8220;That&#8217;s dangerous, that&#8217;s very dangerous. You have all kinds of mess when you don&#8217;t tell the theater commander what you&#8217;re doing.&#8221;</p>
<p>Wilkerson said that almost immediately after assuming his role at the State Department under Colin Powell, he saw JSOC being politicized and developing a close relationship with the executive branch. He saw this begin, he said, after his first Delta Force briefing at Fort Bragg. &#8220;I think Cheney and Rumsfeld went directly into JSOC. I think they went into JSOC at times, perhaps most frequently, without the SOCOM [Special Operations] commander at the time even knowing it. The receptivity in JSOC was quite good,&#8221; says Wilkerson. &#8220;I think Cheney was actually giving McChrystal instructions, and McChrystal was asking him for instructions.&#8221; He said the relationship between JSOC and Cheney and Rumsfeld &#8220;built up initially because Rumsfeld didn&#8217;t get the responsiveness. He didn&#8217;t get the can-do kind of attitude out of the SOCOM commander, and so as Rumsfeld was wont to do, he cut him out and went straight to the horse&#8217;s mouth. At that point you had JSOC operating as an extension of the [administration] doing things the executive branch&#8211;read: Cheney and Rumsfeld&#8211;wanted it to do. This would be more or less carte blanche. You need to do it, do it. It was very alarming for me as a conventional soldier.&#8221;</p>
<p>Wilkerson said the JSOC teams caused diplomatic problems for the United States across the globe. &#8220;When these teams started hitting capital cities and other places all around the world, [Rumsfeld] didn&#8217;t tell the State Department either. The only way we found out about it is our ambassadors started to call us and say, &#8216;Who the hell are these six-foot-four white males with eighteen-inch biceps walking around our capital cities?&#8217; So we discovered this, we discovered one in South America, for example, because he actually murdered a taxi driver, and we had to get him out of there real quick. We rendered him&#8211;we rendered him home.&#8221;</p>
<p>As part of their strategy, Rumsfeld and Cheney also created the Strategic Support Branch (SSB), which pulled intelligence resources from the Defense Intelligence Agency and the CIA for use in sensitive JSOC operations. The SSB was created using &#8220;reprogrammed&#8221; funds &#8220;without explicit congressional authority or appropriation,&#8221; according to the <em>Washington Post</em>. The SSB operated outside the military chain of command and circumvented the CIA&#8217;s authority on clandestine operations. Rumsfeld created it as part of his war to end &#8220;near total dependence on CIA.&#8221; Under US law, the Defense Department is required to report all deployment orders to Congress. But guidelines issued in January 2005 by former Under Secretary of Defense for Intelligence Stephen Cambone stated that Special Operations forces may &#8220;conduct clandestine HUMINT operations&#8230;before publication&#8221; of a deployment order. This effectively gave Rumsfeld unilateral control over clandestine operations.</p>
<p>The military intelligence source said that when Rumsfeld was defense secretary, JSOC was deployed to commit some of the &#8220;darkest acts&#8221; in part to keep them concealed from Congress. &#8220;Everything can be justified as a military operation versus a clandestine intelligence performed by the CIA, which has to be informed to Congress,&#8221; said the source. &#8220;They were aware of that and they knew that, and they would exploit it at every turn and they took full advantage of it. They knew they could act extra-legally and nothing would happen because A, it was sanctioned by DoD at the highest levels, and B, who was going to stop them? They were preparing the battlefield, which was on all of the PowerPoints: &#8216;Preparing the Battlefield.&#8217;&#8221;</p>
<p>The significance of the flexibility of JSOC&#8217;s operations inside Pakistan versus the CIA&#8217;s is best summed up by Senator Dianne Feinstein, chair of the Senate Select Committee on Intelligence. &#8220;Every single intelligence operation and covert action must be briefed to the Congress,&#8221; she said. &#8220;If they are not, that is a violation of the law.&#8221;</p>
<p><strong>Blackwater: Company Non Grata in Pakistan</strong></p>
<p>For months, the Pakistani media has been flooded with stories about Blackwater&#8217;s alleged growing presence in the country. For the most part, these stories have been ignored by the US press and denounced as lies or propaganda by US officials in Pakistan. But the reality is that, although many of the stories appear to be wildly exaggerated, Pakistanis have good reason to be concerned about Blackwater&#8217;s operations in their country. It is no secret in Washington or Islamabad that Blackwater has been a central part of the wars in Afghanistan and Pakistan and that the company has been involved&#8211;almost from the beginning of the &#8220;war on terror&#8221;&#8211;with clandestine US operations. Indeed, Blackwater is accepting applications for contractors fluent in Urdu and Punjabi. The US Ambassador to Pakistan, Anne Patterson, has denied Blackwater&#8217;s presence in the country, stating bluntly in September, &#8220;Blackwater is not operating in Pakistan.&#8221; In her trip to Pakistan in October, Secretary of State Hillary Clinton dodged questions from the Pakistani press about Blackwater&#8217;s rumored Pakistani operations. Pakistan&#8217;s interior minister, Rehman Malik, said on November 21 he will resign if Blackwater is found operating anywhere in Pakistan.</p>
<p>The <em>Christian Science Monitor</em> recently reported that Blackwater &#8220;provides security for a US-backed aid project&#8221; in Peshawar, suggesting the company may be based out of the Pearl Continental, a luxury hotel the United States reportedly is considering purchasing to use as a consulate in the city. &#8220;We have no contracts in Pakistan,&#8221; Blackwater spokesperson Stacey DeLuke said recently. &#8220;We&#8217;ve been blamed for all that has gone wrong in Peshawar, none of which is true, since we have absolutely no presence there.&#8221;</p>
<p>Reports of Blackwater&#8217;s alleged presence in Karachi and elsewhere in the country have been floating around the Pakistani press for months. Hamid Mir, a prominent Pakistani journalist who rose to fame after his 1997 interview with Osama bin Laden, claimed in a recent interview that Blackwater is in Karachi. &#8220;The US [intelligence] agencies think that a number of Al-Qaeda and Taliban leaders are hiding in Karachi and Peshawar,&#8221; he said. &#8220;That is why [Blackwater] agents are operating in these two cities.&#8221; Ambassador Patterson has said that the claims of Mir and other Pakistani journalists are &#8220;wildly incorrect,&#8221; saying they had compromised the security of US personnel in Pakistan. On November 20 the <em>Washington Times</em>, citing three current and former US intelligence officials, reported that Mullah Mohammed Omar, the leader of the Afghan Taliban, has &#8220;found refuge from potential U.S. attacks&#8221; in Karachi &#8220;with the assistance of Pakistan&#8217;s intelligence service.&#8221;</p>
<p>In September, the Pakistani press covered a report on Blackwater allegedly submitted by Pakistan&#8217;s intelligence agencies to the federal interior ministry. In the report, the intelligence agencies reportedly allege that Blackwater was provided houses by a federal minister who is also helping them clear shipments of weapons and vehicles through Karachi&#8217;s Port Qasim on the coast of the Arabian Sea. The military intelligence source did not confirm this but did say, &#8220;The port jives because they have a lot of [former] SEALs and they would revert to what they know: the ocean, instead of flying stuff in.&#8221;</p>
<p><em>The Nation</em> cannot independently confirm these allegations and has not seen the Pakistani intelligence report. But according to Pakistani press coverage, the intelligence report also said Blackwater has acquired &#8220;bungalows&#8221; in the Defense Housing Authority in the city. According to the DHA website, it is a large residential estate originally established &#8220;for the welfare of the serving and retired officers of the Armed Forces of Pakistan.&#8221; Its motto is: &#8220;Home for Defenders.&#8221; The report alleges Blackwater is receiving help from local government officials in Karachi and is using vehicles with license plates traditionally assigned to members of the national and provincial assemblies, meaning local law enforcement will not stop them.</p>
<p>The use of private companies like Blackwater for sensitive operations such as drone strikes or other covert work undoubtedly comes with the benefit of plausible deniability that places an additional barrier in an already deeply flawed system of accountability. When things go wrong, it&#8217;s the contractors&#8217; fault, not the government&#8217;s. But the widespread use of contractors also raises serious legal questions, particularly when they are a part of lethal, covert actions. &#8220;We are using contractors for things that in the past might have been considered to be a violation of the Geneva Convention,&#8221; said Lt. Col. Addicott, who now runs the Center for Terrorism Law at St. Mary&#8217;s University School of Law in San Antonio, Texas. &#8220;In my opinion, we have pressed the envelope to the breaking limit, and it&#8217;s almost a fiction that these guys are not in offensive military operations.&#8221; Addicott added, &#8220;If we were subjected to the International Criminal Court, some of these guys could easily be picked up, charged with war crimes and put on trial. That&#8217;s one of the reasons we&#8217;re not members of the International Criminal Court.&#8221;</p>
<p>If there is one quality that has defined Blackwater over the past decade, it is the ability to survive against the odds while simultaneously reinventing and rebranding itself. That is most evident in Afghanistan, where the company continues to work for the US military, the CIA and the State Department despite intense criticism and almost weekly scandals. Blackwater&#8217;s alleged Pakistan operations, said the military intelligence source, are indicative of its new frontier. &#8220;Having learned its lessons after the private security contracting fiasco in Iraq, Blackwater has shifted its operational focus to two venues: protecting things that are in danger and anticipating other places we&#8217;re going to go as a nation that are dangerous,&#8221; he said. &#8220;It&#8217;s as simple as that.&#8221;</p>
<p><!-- /end .important --></p>
<div><em>Jeremy Scahill, a Puffin Foundation Writing Fellow at The Nation Institute, is the author of the bestselling <a href="http://www.amazon.com/dp/156858394X/ref=nosim/?tag=nationbooks08-20"><em>Blackwater: The Rise of the World&#8217;s Most Powerful Mercenary Army</em></a>, published by Nation Books. He is an award-winning investigative journalist and correspondent for the national radio and TV program <cite>Democracy Now!</cite>.  <a href="http://www.thenation.com/directory/bios/jeremy_scahill">more&#8230;</a></em></div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[SELECT]]></title>
<link>http://thewaterrat.com/2009/11/23/select-16/</link>
<pubDate>Mon, 23 Nov 2009 21:33:43 +0000</pubDate>
<dc:creator>Andrea Favale</dc:creator>
<guid>http://thewaterrat.com/2009/11/23/select-16/</guid>
<description><![CDATA[Boo.com owner made 100m but not from Boo Winbuyer series A funding LinkedIn expands platform in atte]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://eu.techcrunch.com/2009/11/23/boo-com-owner-made-100m-but-not-from-boo/" target="_blank"><span style="color:#b22222;"><strong>Boo.com</strong> owner made 100m but not from Boo</span></a><br />
<a href="http://www.techcrunch.com/2009/11/23/winbuyer-series-a-funding/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+Techcrunch+%28TechCrunch%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;"><strong>Winbuyer</strong> series A funding</span></a><br />
<a href="http://digital.venturebeat.com/2009/11/23/142781/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+Venturebeat+%28VentureBeat%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;"><strong>LinkedIn</strong> expands platform in attempt to one-up Facebook Connect</span></a><br />
<a href="http://www.businessinsider.com/business-news/nov-23-associated-content1-2009-11" target="_blank"><span style="color:#b22222;"><strong>Associated Content</strong> CEO interview</span></a><br />
<a href="http://entrepreneur.venturebeat.com/2009/11/23/sacrifice-your-health-for-your-startup/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+Venturebeat+%28VentureBeat%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;"><strong>Sacrifice your health</strong> for your startup</span></a><br />
<a href="http://thewaterrat.wordpress.com/files/2009/11/hard20work.jpg"><img class="alignleft size-medium wp-image-666" title="hard%20work" src="http://thewaterrat.wordpress.com/files/2009/11/hard20work.jpg?w=300" alt="" width="300" height="225" /></a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[]]></title>
<link>http://computermusic08.wordpress.com/2009/11/23/61/</link>
<pubDate>Mon, 23 Nov 2009 00:52:33 +0000</pubDate>
<dc:creator>Helen  Beech</dc:creator>
<guid>http://computermusic08.wordpress.com/2009/11/23/61/</guid>
<description><![CDATA[Here are two nifty tricks to help you expand your Sibelius  selection tool box.To make it really eff]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://computermusic08.wordpress.com/files/2009/11/music1.png"><img class="aligncenter size-thumbnail wp-image-64" title="Distressed Music" src="http://computermusic08.wordpress.com/files/2009/11/music1.png?w=150" alt="" width="150" height="69" /></a></p>
<p>Here are two nifty tricks to help you expand your Sibelius  selection tool box.To make it really effective open sibelius and try it out straight away &#8211; then make sure you teach someone else the same trick within a day or so.</p>
<p>Selecting just the notes you want in a bar</p>
<p><a href="http://computermusic08.wordpress.com/files/2009/11/selecting-just-the-notes-you-need.png"><img class="aligncenter size-thumbnail wp-image-62" title="selecting just the notes you need" src="http://computermusic08.wordpress.com/files/2009/11/selecting-just-the-notes-you-need.png?w=150" alt="" width="150" height="53" /></a>is as simple as command click on a mac or control click in windows.<br />
BRILLIANT!</p>
<p>You can also copy quickly using the alt key</p>
<p><a href="http://computermusic08.wordpress.com/files/2009/11/alt-click-copy.png"><img class="aligncenter size-thumbnail wp-image-63" title="alt click copy" src="http://computermusic08.wordpress.com/files/2009/11/alt-click-copy.png?w=150" alt="" width="150" height="65" /></a>If you have something selected you can point the arrow/caveat to another bar and hit alt  and like magic you notes appear &#8211; this is faster than cut and paste.</p>
<p>Hopefully these two ideas will give you even more time to do what you love &#8211; writing music. Don&#8217;t forget to go and show somebody else.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Blondie Announces U.S. Tour Dates]]></title>
<link>http://hepara.wordpress.com/2009/11/20/blondie-announces-u-s-tour-dates/</link>
<pubDate>Fri, 20 Nov 2009 21:33:40 +0000</pubDate>
<dc:creator>kronaz</dc:creator>
<guid>http://hepara.wordpress.com/2009/11/20/blondie-announces-u-s-tour-dates/</guid>
<description><![CDATA[(4/7/99, 1 a.m. PST) &#8211; After drumming up plenty of publicity with select promotional appearanc]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>(4/7/99, 1 a.m. PST) &#8211; After drumming up plenty of publicity with select promotional appearances, this summer <strong><a href="http://hepara.wordpress.com">Blondie</a></strong> will stage its first U.S. tour in more than 16 years, beginning May 15 in Boston.</p>
<p>The trek is in support of the band&#8217;s reunion effort, <em><a href="http://hepara.wordpress.com/2009/11/15/blondie-donna-summer/">No Exit</a></em>, which has been greeted with moderate success in the U.S. The album is No. 75 this week in its fifth week on the <em>Billboard</em> 200.</p>
<p>Tickets for the tour, which will run through June 10, will go on sale on Friday (April 9) through <a href="http://mp3vita.net/">www.mp3vita.net </a>and <a href="http://entiregoods.com/">www.entiregoods.com</a>, as well as local ticket outlets, beginning the weekend of April 10.</p>
<p><strong>Ray Waddell</strong>, who covers talent and touring for industry trade publication <em>Amusement Business</em>, expects the tour to do good business. &#8220;There&#8217;s been a lot of media and a lot of buzz,&#8221; he notes.</p>
<p>Here&#8217;s the itinerary for Blondie&#8217;s <em>No Exit</em> tour:</p>
<p>5/15 &#8211; Orpheum, Boston<br />
5/16 &#8211; Massey Hall, Toronto<br />
5/18 &#8211; Tower Theatre, Philadelphia<br />
5/19 &#8211; The Pier, Baltimore<br />
5/23 &#8211; Fox Theatre, Detroit<br />
5/25 &#8211; Fillmore Auditorium, Denver<br />
5/27 &#8211; The Joint, Las Vegas, Nev.<br />
5/28 &#8211; Universal Amphitheatre, Los Angeles<br />
5/29 &#8211; Open Air Theatre, San Diego<br />
5/30 &#8211; Warfield, San Francisco<br />
6/1 &#8211; Paramount, Seattle<br />
6/2 &#8211; Civic, Portland, Ore.<br />
6/10 &#8211; Madison Square Garden Theatre, New York</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[SELECT]]></title>
<link>http://thewaterrat.com/2009/11/20/select-15/</link>
<pubDate>Fri, 20 Nov 2009 21:08:40 +0000</pubDate>
<dc:creator>Andrea Favale</dc:creator>
<guid>http://thewaterrat.com/2009/11/20/select-15/</guid>
<description><![CDATA[Fingertips, a personalised online newspaper thats not so personal airbnb Buffett cuts sweet deal for]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://eu.techcrunch.com/2009/11/20/fingertips-a-personalised-online-newspaper-thats-not-so-personal/" target="_blank"><span style="color:#b22222;"><strong>Fingertips</strong>, a personalised online newspaper thats not so personal</span></a><br />
<a href="http://www.techcrunch.com/2009/11/20/airbnb-groups/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+Techcrunch+%28TechCrunch%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;"><strong>airbnb</strong></span></a><br />
<a href="http://dealbook.blogs.nytimes.com/2009/11/20/buffett-cuts-sweet-deal-for-burlington-northern-loan/" target="_blank"><span style="color:#b22222;"><strong>Buffett </strong>cuts sweet deal for Burlington Northern loan</span></a><br />
<a href="http://dealbook.blogs.nytimes.com/2009/11/20/eu-takes-more-time-to-review-oracle-sun-deal/" target="_blank"><span style="color:#b22222;">EU takes more time to review <strong>Oracle Sun</strong> deal</span></a><br />
<a href="http://eu.techcrunch.com/2009/11/20/european-startups-need-to-work-as-hard-as-valley-ones-or-forget-it/?replytocom=283040#addcomment" target="_blank"><span style="color:#b22222;"><strong>European startups</strong> need to work as hard as Valley ones or forget it</span></a></p>
<p><a href="http://thewaterrat.wordpress.com/files/2009/11/hard-work.jpg"><img class="alignleft size-medium wp-image-628" title="HARD-WORK" src="http://thewaterrat.wordpress.com/files/2009/11/hard-work.jpg?w=300" alt="" width="300" height="162" /></a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[SELECT]]></title>
<link>http://thewaterrat.com/2009/11/19/select-14/</link>
<pubDate>Thu, 19 Nov 2009 20:29:36 +0000</pubDate>
<dc:creator>Andrea Favale</dc:creator>
<guid>http://thewaterrat.com/2009/11/19/select-14/</guid>
<description><![CDATA[As Aol heads for an Ipo it leaves 2500 employees behind Vevo sets Dec 8 launch date Twitter founder:]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://www.techcrunch.com/2009/11/19/as-aol-heads-for-an-ipo-it-leaves-2500-employees-behind/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+Techcrunch+%28TechCrunch%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;">As <strong>Aol</strong> heads for an Ipo it leaves 2500 employees behind</span></a><br />
<a href="http://gigaom.com/2009/11/18/vevo-sets-dec-8-launch-date/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+OmMalik+%28GigaOM%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;"><strong>Vevo</strong> sets Dec 8 launch date</span></a><br />
<a href="http://www.newser.com/story/74419/twitter-founder-murdoch-will-fail-fast.html?utm_source=syn&#38;utm_medium=rss&#38;utm_campaign=bus" target="_blank"><span style="color:#b22222;"><strong>Twitter</strong> founder: Murdoch will fail fast</span></a><br />
<a href="http://www.groundreport.com/Business/GM-Announces-It-Will-Pay-Back-Gov-t-Loan-With-Gov-/2911929" target="_blank"><span style="color:#b22222;"><strong>GM</strong> announces it will pay back Government loan with the Government&#8217;s money</span></a><br />
<a href="http://www.businessinsider.com/henry-blodget-felix-salmon-henry-blodget-should-be-banned-from-the-industry-2009-11" target="_blank"><span style="color:#b22222;">Felix Salmon: <strong>Henry Blodget</strong> should be banned from the industry</span></a></p>
<p><a href="http://thewaterrat.wordpress.com/files/2009/11/delete.jpg"><img class="alignleft size-medium wp-image-589" title="delete" src="http://thewaterrat.wordpress.com/files/2009/11/delete.jpg?w=300" alt="" width="300" height="300" /></a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Query SELECT untuk record yang mengandung apostropi (')]]></title>
<link>http://ndereklangkung.wordpress.com/2009/11/19/query-select-untuk-record-yang-mengandung-apostropi-2/</link>
<pubDate>Thu, 19 Nov 2009 02:06:18 +0000</pubDate>
<dc:creator>ndereklangkung</dc:creator>
<guid>http://ndereklangkung.wordpress.com/2009/11/19/query-select-untuk-record-yang-mengandung-apostropi-2/</guid>
<description><![CDATA[Sebenarnya aku kurang begitu jago soal SQL Query. Yang aku bisa baru sebatas level &#8216;permukaan]]></description>
<content:encoded><![CDATA[Sebenarnya aku kurang begitu jago soal SQL Query. Yang aku bisa baru sebatas level &#8216;permukaan]]></content:encoded>
</item>
<item>
<title><![CDATA[SELECT]]></title>
<link>http://thewaterrat.com/2009/11/18/select-13/</link>
<pubDate>Wed, 18 Nov 2009 18:49:21 +0000</pubDate>
<dc:creator>Andrea Favale</dc:creator>
<guid>http://thewaterrat.com/2009/11/18/select-13/</guid>
<description><![CDATA[Yahoo! and Microsoft poised to finally sign definitive search and ad agreement The one sentence emai]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://kara.allthingsd.com/20091118/exclusive-yahoo-and-microsoft-poised-to-finally-sign-definitive-search-and-ad-agreement/" target="_blank"><span style="color:#b22222;"><strong>Yahoo!</strong> and <strong>Microsoft</strong> poised to finally sign definitive search and ad agreement</span></a><br />
<a href="http://www.businessinsider.com/the-one-sentence-e-mail-turndown-2009-11?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+typepad%2Falleyinsider%2Fsilicon_alley_insider+%28Silicon+Alley+Insider%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;">The one sentence email <strong>turndown</strong></span></a><br />
<a href="http://venturebeat.com/2009/11/18/modern-warfare-2-continues-to-blow-away-entertainment-records/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+Venturebeat+%28VentureBeat%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;"><strong>Modern Warfare 2</strong> continues to blow away entertainment records</span></a><br />
<a href="http://eu.techcrunch.com/2009/11/18/burda-buys-25-stake-in-xing/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+Techcrunch+%28TechCrunch%29" target="_blank"><span style="color:#b22222;"><strong>Burda</strong> buys 25% stake in Xing</span></a><br />
<a href="http://www.businessinsider.com/hulu-gets-some-music-videos-from-emi-2009-11?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+typepad%2Falleyinsider%2Fsilicon_alley_insider+%28Silicon+Alley+Insider%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;"><strong>Hulu</strong> gets some music videos from Emi</span></a></p>
<p><span style='text-align:center; display: block;'><object width='425' height='350'><param name='movie' value='http://www.youtube.com/v/_CoYGexR5Rk&#038;rel=0&#038;fs=1&#038;showsearch=0&#038;hd=0' /><param name='allowfullscreen' value='true' /><param name='wmode' value='transparent' /><embed src='http://www.youtube.com/v/_CoYGexR5Rk&#038;rel=0&#038;fs=1&#038;showsearch=0&#038;hd=0' type='application/x-shockwave-flash' allowfullscreen='true' width='425' height='350' wmode='transparent'></embed></object></span></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Problema com datetime do MySql e PHP]]></title>
<link>http://dilbertorosa.wordpress.com/2009/11/18/problema-com-datetime-do-mysql-e-php/</link>
<pubDate>Wed, 18 Nov 2009 11:43:24 +0000</pubDate>
<dc:creator>dilbertorosa</dc:creator>
<guid>http://dilbertorosa.wordpress.com/2009/11/18/problema-com-datetime-do-mysql-e-php/</guid>
<description><![CDATA[Hoje Eu e a Luciane enfrentamos um problema: Realizar um select em um campo datetime do MySql. Parec]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Hoje Eu e a Luciane enfrentamos um problema: Realizar um select em um campo datetime do MySql. Parece simples? Mas não foi!</p>
<p>Em nossas consultas sempre realizamos pesquisas no banco de dados com campos do tipo datetime, porém nunca enfrentamos a situação em que o resultado sempre vinha vazio sendo que temos dados em banco. Desta forma começamos a perguntar: Porque o aqua (nossa ferramenta para consultas à banco de dados) não traz o resultado?</p>
<p>Nosso select no aqua era o seguinte:<br />
<strong><br />
select * from tabela where campo_data = current_date</strong></p>
<p>Bom, normalmente, para outras consultas esse comando sql funcionaria. Desta vez não foi bem assim.</p>
<p>Dando uma analisada no conteúdo da tabela no banco, identificamos as seguintes datas:</p>
<p>16/11/2009 11:39:00<br />
16/11/2009 10:30:03</p>
<p>Desta forma, podemos identificar que, apesar de serem mesmas datas, o datetime permite gravação de hora, minuto e segundos. Essa foi a primeira pista.</p>
<p>A segundo pergunta foi: Como estão sendo gravados estes dados?</p>
<p>Identificamos que no PHP, na realização do insert em banco de dados, o programador pegou a data atual com o seguinte comando: &#8220;now&#8221;. Agora temos a segunda pista. O comando &#8220;now&#8221; do PHP traz a data atual, acompanhada de hora, minuto e segundos! Assim, quando era realizado insert em banco, era gravado a data com a hora atual, porém na busca estavamos utilizando apenas a data. O resultado do SQL era vazio pois a data era a mesma mas a hora não.</p>
<p>Como resolver?</p>
<p>A idéia inicial foi alterar a função PHP de &#8216;now&#8217; para date(&#8216;Y-m-d&#8217;). E deu certo!</p>
<p>Ao utilizar a função &#8220;date&#8221;, o PHP grava a data no campo, com a hora zerada. Desta forma a consulta sql desconsidera a hora para aquela linha, trazendo o registro. É isso!</p>
<p>Abraço.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Advanced radio button grouping with jQuery]]></title>
<link>http://calisza.wordpress.com/2009/11/18/advanced-radio-button-grouping-with-jquery/</link>
<pubDate>Wed, 18 Nov 2009 10:51:53 +0000</pubDate>
<dc:creator>calisza</dc:creator>
<guid>http://calisza.wordpress.com/2009/11/18/advanced-radio-button-grouping-with-jquery/</guid>
<description><![CDATA[I was asked to do something rather interesting with some radio button inputs the other day. I haven]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I was asked to do something rather interesting with some radio button inputs the other day. I haven&#8217;t come across this particular problem before and google didn&#8217;t return anything helpful, so I decided to share what I came up with.</p>
<h2>First, the scenario</h2>
<p>We have a standard form with 4 radio button groups. Each group has 4 radio buttons labeled from<em> &#8220;1&#8243; </em>to <em>&#8220;4&#8243;</em>. Now, when the user selects<em> &#8220;option 1&#8243;</em> in <em>&#8220;group 1&#8243;</em>, all the remaining <em>&#8220;option 1&#8243;</em> items need to be disabled. To see an example in action, <a title="Advanced Radio demo" href="http://flexidev.co.za/dev/code/advancedradio/" target="_blank">you can view the demo here</a>.</p>
<h2>The problem</h2>
<p>When I first started, I thought that it&#8217;s simply a matter of giving each <em>&#8220;option&#8221;</em> (regardless of group) a common class name &#8211; then just disabling all other options with the same class name. That works, to a point, but what if the user changes his mind and selects another option ? Now I had to find all previously disabled options, re-enable them and start all over again.</p>
<h2>The solution</h2>
<p>Essentially what I came up with was a basic nested loop to handle setting and unsetting the relevant <em>&#8220;disabled&#8221;</em> attributes. To achieve this, first we assign all <em>&#8220;option 1&#8243;</em> a class of <em>&#8220;number1&#8243;</em>, <em>&#8220;option 2&#8243;</em> a class of <em>&#8220;number2&#8243;</em> and so on.</p>
<p>Next, we run a basic <strong><em>for loop</em></strong>, and go through each <em>&#8220;number&#8221;</em> class (i.e. number1 to number4). For each class, we call a function. Inside this function is another loop &#8211; this time iterating over each radio button assigned the current class name. Using this loop, we remove any <em>&#8220;disabled&#8221; </em>attributes which may have been assigned previously. We also find out which item in that group is currently selected (if any) &#8211; this is so we can run a second loop to disable all those options not currently selected. Confused ? Now might be a good time to go through the code</p>
<h2>The code</h2>
<pre class="brush: jscript;">
$(function(){
		// fire our code when a radio button has been selected
		$(&#34;input[type=radio]&#34;).change(function(){
			var name = $(this).attr(&#34;name&#34;); // get the current button's group name
			$(&#34;input[name=&#34;+name+&#34;]&#34;).removeAttr(&#34;selected&#34;); // first we deselect &#34;all&#34; radio buttons within the same group
			$(this).attr(&#34;selected&#34;,&#34;selected&#34;); // make sure our currently &#34;changed&#34; button is selected
			for(i=1;i&#60;=4;i++){ // go through the 4 radio classes
				processRadio(&#34;.radio&#34;+i);
			}
		});
		/**
			Loops through each item with same &#34;class&#34; name and disables/enables where appropriate
		**/
		function processRadio(class){
			var empty;
			var id = &#34;&#34;;
			var buttons = $(class); // read all buttons with the specified class name into a jQuery object
			buttons.each(function(){ // loop through each item
				var me = $(this);
				var isSelected = me.attr(&#34;selected&#34;); // bool value, based on whether the &#34;selected&#34; attribute is present or not
				me.removeAttr(&#34;disabled&#34;); // clear the disabled attribute if present
				me.siblings(&#34;label&#34;).removeClass(&#34;disabled&#34;); // same with the associated label element
				if (isSelected != empty &#38;&#38; isSelected != &#34;&#34;){
					id = $(this).attr(&#34;id&#34;); // set our tmp id var to our currently selected item
				}
			});
			// make sure we have an id, otherwise we'll get an error
			if (id != empty &#38;&#38; id != &#34;&#34;){
				buttons.each(function(){ // loop through each radio button once again
					if ($(this).attr(&#34;id&#34;) != id){ // set the disabled attributes if id attribute doesn't match our tmp id var
						$(this).attr(&#34;disabled&#34;, &#34;disabled&#34;).siblings(&#34;label&#34;).addClass(&#34;disabled&#34;);
					}
				});
			}
		}

	});
</pre>
<p>I&#8217;ve commented as best I could, which hopefully makes more sense than my rambling above. Once again, there is a <a title="Advanced Radio demo" href="http://flexidev.co.za/dev/code/advancedradio/" target="_blank">working demo available</a> for you to play with. Be sure to have a look at the markup as well, might clear up a few questions.</p>
<p>I strongly suspect that there&#8217;s a more efficient method for achieving the same result &#8211; so if you have a better suggestion, tweak or link please let me know &#8211; I&#8217;d greatly appreciate it.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[SELECT]]></title>
<link>http://thewaterrat.com/2009/11/17/select-12/</link>
<pubDate>Tue, 17 Nov 2009 18:09:14 +0000</pubDate>
<dc:creator>Andrea Favale</dc:creator>
<guid>http://thewaterrat.com/2009/11/17/select-12/</guid>
<description><![CDATA[Where the internet lives MySpace close to acquiring iMeem Airport Wi-Fi users an affluent lot: study]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://www.ft.com/cms/s/0/80e69da4-d2e4-11de-af63-00144feabdc0.html?ftcamp=rss&#38;nclick_check=1" target="_blank"><span style="color:#b22222;">Where the <strong>internet</strong> lives</span></a><br />
<a href="http://www.techcrunch.com/2009/11/16/myspace-close-to-acquiring-imeem/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+Techcrunch+%28TechCrunch%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;"><strong>MySpace</strong> close to acquiring iMeem</span></a><br />
<a href="http://gigaom.com/2009/11/17/airport-wi-fi-users-an-affluent-lot-study/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+OmMalik+%28GigaOM%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;">Airport <strong>Wi-Fi</strong> users an affluent lot: study</span></a><br />
<a href="http://tims-boot.blogspot.com/2009/11/interview-with-joobili-boss-jared_17.html" target="_blank"><span style="color:#b22222;">Interview with <strong>Joobili</strong>&#8217;s boss</span></a><br />
<a href="http://www.techcrunch.com/2009/11/16/rockyou-raises-a-whopper-50-million-in-venture-capital/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+Techcrunch+%28TechCrunch%29" target="_blank"><span style="color:#b22222;"><strong>RockYou</strong> raises a whopper 50 million in venture capital</span></a><br />
<a href="http://www.businessinsider.com/the-problem-with-aols-media-strategy-2009-11?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+typepad%2Falleyinsider%2Fsilicon_alley_insider+%28Silicon+Alley+Insider%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;">The problem with <strong>Aol&#8217;s media strategy</strong></span></a></p>
<p><a href="http://thewaterrat.wordpress.com/files/2009/11/aol.jpg"><img class="alignleft size-full wp-image-558" title="aol" src="http://thewaterrat.wordpress.com/files/2009/11/aol.jpg" alt="" width="212" height="212" /></a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[NO SELECT]]></title>
<link>http://thewaterrat.com/2009/11/16/no-select/</link>
<pubDate>Mon, 16 Nov 2009 23:20:30 +0000</pubDate>
<dc:creator>Andrea Favale</dc:creator>
<guid>http://thewaterrat.com/2009/11/16/no-select/</guid>
<description><![CDATA[Annoying and persistent internet connection problems today. So, No Select.]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Annoying and persistent internet connection problems today. So, No Select.</p>
<p><a href="http://thewaterrat.wordpress.com/files/2009/11/no-signal.jpg"><img class="alignleft size-full wp-image-543" title="no signal" src="http://thewaterrat.wordpress.com/files/2009/11/no-signal.jpg" alt="" width="146" height="160" /></a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Women's Shoes - How to Select the Best Ones]]></title>
<link>http://womensshoesonline.wordpress.com/2009/11/16/womens-shoes-how-to-select-the-best-ones/</link>
<pubDate>Mon, 16 Nov 2009 05:56:54 +0000</pubDate>
<dc:creator>name2110</dc:creator>
<guid>http://womensshoesonline.wordpress.com/2009/11/16/womens-shoes-how-to-select-the-best-ones/</guid>
<description><![CDATA[The woman is the footwear industry in recent years has become in recent years due to the increase in]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p> The woman is the footwear industry in recent years has become in recent years due to the increase in demand and because of the fact that it has grown new styles and designs that come every year. </p>
<p> One year it&#39;s the season of Ugg boots and the rest of the year it&#39;s the season of sandals. However, there are a lot of manufactures who make these shapes out there. These <b>shoes are</b> made from the top companies in all shapes and sizes. Each company takesCare of the <b>shoes</b> in those basic forms and styles. </p>
<p> The main styles are the ankle boots, Mary Janes, knee boots, sandals, slides, Thigh Boots, and T-straps. Now, within each style there are various other styles such as the ankle strap are available, block heels, sandals, platform, pointed, rounded tip, and sling back wedges. </p>
<p> In relation to the size of the most common sizes are small, wide and extra wide <b>shoes.</b> These <b>shoes</b> also depending on the type ofHeight of the heels. </p>
<p> That said, the general trend in fashion <b>footwear</b> will be set up by the people whom we admire, like all female Hollywood inside and the top end designers. These designers start their <b>shoes</b> and other accessories for every season and then hope that the trend is to cat this season and good money for them. </p>
<p> If you are a woman looking for <b>shoes</b> then the best thing you have to do is ensure that you know everything about it,latest designs and styles on the market. </p>
<p> The author writes about the <b>shoes</b> and Women&#39;s Women&#39;s <b>Golf Shoes</b> </p>
<p> <a href="http://babyernahrungshop.blogspot.com" rel="dofollow" title="Billig Baby Ernährung &#38; Stillen Shop">Billig Baby Ernährung &#38; Stillen Shop</a> </p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[ORACLE , Introduccion al SQL]]></title>
<link>http://margotu.wordpress.com/2009/11/15/oracle-introduccion-al-sql/</link>
<pubDate>Sun, 15 Nov 2009 11:42:20 +0000</pubDate>
<dc:creator>Javier Aparicio</dc:creator>
<guid>http://margotu.wordpress.com/2009/11/15/oracle-introduccion-al-sql/</guid>
<description><![CDATA[Structured Query Language o Lenguaje de Consultas Estructurado. Es el lenguaje que permite la comuni]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><em>Structured Query Language</em> o Lenguaje de Consultas Estructurado. Es el lenguaje que permite la comunicación con el Sistema Gestor de Bases de Datos (Oracle en nuestro caso).</p>
<p>El SQL es un lenguaje unificado</p>
<p>Lo utilizan todo tipo de usuarios, desde el administrador de la base de datos, DBA, hasta el usuario final.</p>
<p><!--more--></p>
<p>El SQL es un lenguaje no procedimental.</p>
<p>El usuario especifica <em>Qué</em> quiere, no <em>Cómo</em> ni <em>Dónde</em> conseguirlo.</p>
<p>El SQL es relacionalmente completo.</p>
<p>Permite la realización de cualquier consulta de datos.</p>
<p>SQL= DDL + DML</p>
<p>Las sentencias del SQL se clasifican como parte del DDL o del DML.</p>
<p>Lenguaje de Definición de Datos, DDL</p>
<p>sentencias del SQL que permiten definir los objetos de la Base de Datos (<tt>create</tt>, <tt>revoke</tt>, <tt>grant</tt>, <tt>alter</tt>, etc.). Cuando se definen dichos objetos se almacenan en el diccionario de datos.</p>
<p>Lenguaje de Manipulación de Datos, DML</p>
<p>sentencias del SQL que se utilizan para manejar los datos de la base de datos (<tt>select</tt>, <tt>insert</tt>, <tt>update</tt>, <tt>delete</tt>, etc).</p>
<p><tt>commit</tt>/<tt>rollback</tt></p>
<p>cada vez que se realiza alguna operación en la base de datos se realiza no sobre la tabla en sí, sino sobre una copia local de la misma. Así, si queremos que los resultados de la modificación se trasladen a la base de datos y perduren en el tiempo hay que confirmar dicha operación con el comando <tt>commit</tt>. También se puede impedir que los últimos cambios lleguen a efectuarse con <tt>rollback</tt>, aunque existen algunas sentencias SQL que se &#8216;autoconfirman&#8217; y no se pueden volver atrás.</p>
<p>Diccionario de la Base de Datos</p>
<p>Guarda la definición de todos los objetos almacenados en la base de datos; sus características, restricciones, privilegios, relaciones entre ellos, etc.</p>
<hr size="2" /><strong>2 Tipos de Sentencias </strong></p>
<hr size="2" />Las sentencias SQL pertenecen a dos categorías principales: Lenguaje de Definición de Datos, DDL y Lenguaje de Manipulación de Datos, DML. Estos dos lenguajes no son lenguajes en sí mismos, sino que es una forma de clasificar las sentencias de lenguaje SQL en función de su cometido. La diferencia principal reside en que el DDL crea objetos en la base de datos y sus efectos se pueden ver en el diccionario de la base de datos; mientras que el DML es el que permite consultar, insertar, modificar y eliminar la información almacenada en los objetos de la base de datos.</p>
<p>Cuando se ejecutan las sentencias DDL de SQL, el SGBD confirma la transacción actual antes y después de cada una de las sentencias DDL. En cambio, las sentencias DML no llevan implícito el <tt>commit</tt> y se pueden deshacer. Existe pues un problema al mezclar sentencias DML con DDL, ya que estas últimas pueden confirmar las primeras de manera involuntaria e implicita, lo que en ocasiones puede ser un problema.</p>
<p>A continuación se presenta una tabla con las sentencias SQL más comunes, clasificadas según el lenguaje al que pertenecen.</p>
<table border="1" cellpadding="0" width="90%">
<tbody>
<tr>
<td><strong><em>Sentencia DDL</em></strong></td>
<td><strong><em>Objetivo</em></strong></td>
</tr>
<tr>
<td>Alter procedure</td>
<td>Recompilar un procedimiento almacenado.</td>
</tr>
<tr>
<td>Alter Table</td>
<td>Añadir o redefinir una columna, modificar la asignación de almacenamiento.</td>
</tr>
<tr>
<td>Analyze</td>
<td>Recoger estadísticas de rendimiento sobre los objetos de la BD para utilizarlas en el optimizador basado en costes.</td>
</tr>
<tr>
<td>Create Table</td>
<td>Crear una tabla.</td>
</tr>
<tr>
<td>Create Index</td>
<td>Crear un índice.</td>
</tr>
<tr>
<td>Drop Table</td>
<td>Eliminar una tabla.</td>
</tr>
<tr>
<td>Drop Index</td>
<td>Eliminar un índice.</td>
</tr>
<tr>
<td>Grant</td>
<td>Conceder privilegios o papeles, roles, a un usuario o a otro rol.</td>
</tr>
<tr>
<td>Truncate</td>
<td>Eliminar todas las filas de una tabla.</td>
</tr>
<tr>
<td>Revoke</td>
<td>Retirar los privilegios de un usuario o rol de la base de datos.</td>
</tr>
<tr>
<td><strong><em>Sentencia DML</em></strong></td>
<td><strong><em>Objetivo</em></strong></td>
</tr>
<tr>
<td>Insert</td>
<td>Añadir filas de datos a una tabla.</td>
</tr>
<tr>
<td>Delete</td>
<td>Eliminar filas de datos de una tabla.</td>
</tr>
<tr>
<td>Update</td>
<td>Modificar los datos de una tabla.</td>
</tr>
<tr>
<td>Select</td>
<td>Recuperar datos de una tabla.</td>
</tr>
<tr>
<td>Commit</td>
<td>Confirmar como permamentes las modificaciones realizadas.</td>
</tr>
<tr>
<td>Rollback</td>
<td>Deshacer todas las modificaciones realizadas desde la última confirmación.</td>
</tr>
</tbody>
</table>
<hr size="2" /><strong>3 SQL*Plus </strong></p>
<hr size="2" />La herramienta que nos proporciona ORACLE para interactuar con la base de datos se llama SQL*Plus. Básicamente, es un intérprete SQL con algunas opciones de edición y formateo de resultados.</p>
<p>Antes de ver la manera de conectarse a SQL*Plus, conviene tener claros algunos conceptos:</p>
<p>Usuario/Clave</p>
<p>Para poder acceder a una base de datos gestionada por ORACLE debemos ser un usuario autorizado de la misma y conocer la palabra clave, <em>password</em>, asociada al usuario.</p>
<p>Variable de ambiente <tt>ORACLE_SID</tt></p>
<p>Indica la base de datos con la que vamos a trabajar.<br />
<strong>3.1 Conexión </strong></p>
<p>Para entar en SQL*Plus se debe ejecutar el comando</p>
<pre> 
$ sqlplus usuario/passwd</pre>
<p>donde le indicamos al SGBD Oracle quién somos y nuestra palabra clave.</p>
<p>Si la configuración del SGBD Oracle se corresponde a una configuración cliente-servidor asentada sobre una red (SQL*Net v2) deberemos indicar, además, el sevicio (o base de datos) con el que queremos contactar. Esto se hace colocando el símbolo <tt>@</tt> antes del nombre del servicio como se indica a continuación:</p>
<pre> 
$ sqlplus usuario/passwd@servicio</pre>
<p>Otra circunstancia que hay que tener en cuenta a la hora de conectarnos a SQL*Plus es el modo establecido por el DBA para la autentificación del usuario de la base de datos. La primera posibilidad es que recaiga sobre el SGBD Oracle la autentificación de los usuarios, por lo que tendremos que darle nuestro nombre de usuario y la palabra de paso. Pero existe la posibilidad de que el SGBD Oracle deje en manos del Sistema Operativo esta responsabilidad. Así, no será necesario demostrarle al SGBD Oracle quién somos ya que el SO se ha encargado previamente de comprobar que todo es correcto. En este segundo caso, el comando de conexión con SQL*Plus debe omitir el nombre de usuario y la palabra clave, pero manteniendo el resto de esta manera:</p>
<pre> 
$ sqlplus /@servicio</pre>
<p>Una vez que hemos conseguido entrar en SQL*Plus nos presenta el <em>prompt</em> y espera la insercción de sentencias SQL. Todas las sentencias deben acabar con un &#8216;;&#8217;. Una sentencia puede continuar en varias líneas, que SQL*Plus va numerando. Si queremos anular la sentencia actual podemos hacerlo colocando un &#8216;.&#8217; como único carácter en una línea. Si queremos volver a ejecutar la última sentencia se puede hacer con el comando &#8216;/&#8217;. Si queremos ejecutar las sentencias que almacena un fichero .sql podemos hacerlo anteponiendo el símbolo &#8216;@&#8217; al nombre del fichero.</p>
<p>Para cerrar la sesión vale con teclear &#8216;exit&#8217;.<br />
<strong>3.2 Posibilidades de Edición </strong></p>
<p>SQL*Plus almacena en un <em>buffer</em> la última sentencia SQL introducida. El <em>buffer</em> mantiene sólo una sentencia cada vez, y si se introduce una nueva sentencia se sobreescribe sobre la anterior.</p>
<p>La sentencia en el <em>buffer</em> puede ser recuperada para ejecutarla de nuevo con los comandos:</p>
<ul>
<li><tt>RUN</tt> que visualiza la sentencia en el <em>buffer</em> antes de ejecutarla;</li>
<li><tt>/</tt> que ejecuta la sentencia sin visualizarla.</li>
</ul>
<p>SQL*Plus también nos permite editar la sentencia SQL alamacenada en el <em>buffer</em> mediante un sencillo (y limitado) editor en línea, cuyos comandos se enumeran a continuación:</p>
<table border="1" cellpadding="0" width="90%">
<tbody>
<tr>
<td><strong><em>Comando</em></strong></td>
<td><strong><em>Abreviatura</em></strong></td>
<td><strong><em>Descripción</em></strong></td>
</tr>
<tr>
<td>APPEND texto</td>
<td>A texto</td>
<td>Añade texto al final de la línea.</td>
</tr>
<tr>
<td>CHANGE/fuente/destino</td>
<td>C/fuente/destino</td>
<td>Cambia el contenido &#8216;fuente&#8217; por el &#8216;destino&#8217;</td>
</tr>
<tr>
<td>CHANGE/texto</td>
<td>C/texto</td>
<td>Quita &#8216;texto&#8217; de una línea.</td>
</tr>
<tr>
<td>CLEAR BUFFER</td>
<td>CL BUFF</td>
<td>Borra el <em>buffer</em></td>
</tr>
<tr>
<td>DEL</td>
<td>DEL</td>
<td>Borra una línea.</td>
</tr>
<tr>
<td>INPUT</td>
<td>I</td>
<td>Inserta una o más líneas.</td>
</tr>
<tr>
<td>INPUT texto</td>
<td>I texto</td>
<td>Inserta una línea con &#8216;texto&#8217;.</td>
</tr>
<tr>
<td>LIST</td>
<td>L</td>
<td>Lista las líneas del <em>buffer</em></td>
</tr>
<tr>
<td>LIST n</td>
<td>L n ó n</td>
<td>Lista la línea n-ésima.</td>
</tr>
<tr>
<td>LIST *</td>
<td>L *</td>
<td>Lista la línea actual.</td>
</tr>
<tr>
<td>LIST LAST</td>
<td>L LAST</td>
<td>Lista la última línea.</td>
</tr>
<tr>
<td>LIST m n</td>
<td>L m n</td>
<td>Lista las líneas desde la m-ésima a la n-ésima.</td>
</tr>
</tbody>
</table>
<p>Al contenido del <em>buffer</em> también se puede acceder desde el editor del Sistema Operativo. Así, el buffer podrá ser manipulado con las posibilidades del editor con el que estemos acostumbrados a trabajar. Al salir del editor se devuelve el control al SQL*Plus. Para conseguir trabajar con el editor del Sistema Operativo basta con colocar la variable <tt>DEFINE_EDITOR</tt> y luego llamar al editor.</p>
<pre>SQL&#62; define_editor=vi
SQL&#62; edit
 </pre>
<p><strong>3.3 Utilización de Ficheros </strong></p>
<p>SQL*Plus considera dos tipos de ficheros: de <em>spool</em> y de comandos.</p>
<p>Un <strong>fichero de <em>spool</em></strong> almacena los resultados de una consulta (o varias) en un fichero con la extensión .lst (o lo manda a la impresora).</p>
<p>Los comandos asociados con los ficheros <em>spool</em> son</p>
<p><tt>SPOOL fichero</tt></p>
<p>Manda el resultado de las consultas al fichero.</p>
<p><tt>SPOOL OUT</tt></p>
<p>Manda el resultado de las consultas a la impresora.</p>
<p><tt>SPOOL OFF</tt></p>
<p>Cierra el fichero de <em>spool</em>.</p>
<p><tt>EXIT</tt></p>
<p>Al salir de SQL*Plus se cierran los ficheros de <em>spool</em>.</p>
<p>Los <strong>archivos de comandos</strong> almacenan comandos SQL y SQL*Plus para ser editado, almacenado y/o ejecutado; y tienen por defecto la extensión .sql :</p>
<ul>
<li>Para editarlo se puede utilizar el comando <tt>edit fichero</tt>.</li>
<li>Para ejecutarlo se utilizará el comando <tt>START fichero</tt> o <tt>@fichero</tt></li>
</ul>
<p>El SQL*Plus nos proporciona más posibilidades en relación con los ficheros de comandos, la comunicación con el usuario final y la generación de informes. Pero antes de ver este tipo de cosas, es mejor que sigamos profundizando en el conocimiento del lenguaje SQL. Al final del curso se puede se encuentra un capítulo con algunas de las cosillas que quedan por contar del SQL*Plus.</p>
<p><strong>4 Creación </strong></p>
<hr size="2" />La primera fase de cualquier base de datos comienza siempre con sentencias DDL, ya que antes de poder almacenar información debemos definir los objetos básicos donde agrupar la información. Los objetos básicos con que trabaja SQL son las tablas. Una tabla es un conjunto de celdas agrupadas en filas y columnas donde se almacenan elementos de información.</p>
<p>Antes de llevar a cabo la creación de una tabla conviene planificar:</p>
<ul>
<li>nombre de la tabla,</li>
<li>nombre de cada columna,</li>
<li>tipo y tamaño de los datos almacenados en cada columna,</li>
<li>información adicional, restricciones, etc.</li>
</ul>
<p>Hay que tener en cuenta también ciertas restricciones en la formación de los nombres de las tablas: longitud máxima de 30 caracteres, no puede haber nombres de tabla duplicados, deben comenzar con un carácter alfabético, permitir caracteres alfanuméricos y el guión bajo &#8216;_&#8217;, y Oracle no distingue entre mayúsculas y minúsculas.</p>
<p>La sintaxis del comando que permite crear un tabla es la siguiente:</p>
<pre> 
CREATE TABLE [esquema.]tabla ({columna tipoColumna [NOT NULL],}<sup>+</sup>,
       {CONSTRAINT nombreRestricción
          {UNIQUE ([column,]<sup>+</sup>)&#124;
           DEFAULT expresion&#124;
           CHECK (condicion)&#124;
           PRIMARY KEY ([column,]<sup>+</sup>)&#124;
           FOREIGN KEY (column) REFERENCES tabla(columna)},}<sup>*</sup>)</pre>
<p>Del examen de la sintaxis de la sentencia <tt>Create Table</tt> se pueden concluir que necesitamos conocer los distintos tipos de columna y las distintas restricciones que se pueden imponer al contenido de las columnas. Vayamos por partes.<br />
<strong>4.1 Tipos de Columnas </strong></p>
<p>Existen varios tipos de datos en SQL. De esta manera, cada columna puede albergar una información de naturaleza distinta. Los tipos de datos más comunes y sus características se resumen en la siguiente tabla.</p>
<table border="1" cellpadding="0" width="90%">
<tbody>
<tr>
<td><strong><em>Tipo de Dato</em></strong></td>
<td><strong><em>Descripción</em></strong></td>
</tr>
<tr>
<td><tt>VARCHAR2(tamaño)</tt></td>
<td>Almacena datos de tipo carácter alfanumérico de longitud variable, con un tamaño máximo de 2.000.</td>
</tr>
<tr>
<td><tt>CHAR(tamaño)</tt></td>
<td>Almacena datos de tipo carácter alfanumérico de longitud fija, con un tamaño máximo de 255.</td>
</tr>
<tr>
<td><tt>LONG</tt></td>
<td>Almacena datos de tipo carácter alfanumérico de longitud variable con un tamaño máximo de hasta 2 Gb.</td>
</tr>
<tr>
<td><tt>NUMBER(dig,dec)</tt></td>
<td>Almacena datos numéricos de <tt>dig</tt> dígitos, de los cuales <tt>dec</tt> son decimales. El tamaño máximo es de 38 dígitos.</td>
</tr>
<tr>
<td><tt>DATE</tt></td>
<td>Almacena fechas desde el 1-Ene-4712 AC hasta el 31-Dic-4712 DC.</td>
</tr>
<tr>
<td><tt>RAW(tamaño)</tt></td>
<td>Almacena datos de longitud variable, con un tamaño máximo de 255 bytes.</td>
</tr>
<tr>
<td><tt>LONG RAW</tt></td>
<td>Almacena datos de longitud variable, con un tamaño máximo de 2 Gb.</td>
</tr>
</tbody>
</table>
<p><strong>4.2 Restricciones </strong></p>
<p>Las restricciones de los datos se imponen para asegurarnos que los datos cumplen con una serie de condiciones predefinidas para cada tabla. Estas restricciones ayudan a conseguir la integridad de referencia: todas las referencias dentro de una BD son válidas y todas las restricciones se han cumplido.</p>
<p>Las restricciones se van a definir acompañadas por un nombre, lo que permitirá activarlas o desactivarlas según sea el caso; o también mezcladas en la definiciones de las columnas de la tabla. A continuación vamos a describir cada una de las restricciones mencionadas.</p>
<p><tt>NOT NULL</tt></p>
<p>Establece la obligatoriedad de que esta columna tenga un valor no nulo. Se debe especificar junto a la columna a la que afecta. Los valores nulos no ocupan espacio, y son distintos a 0 y al espacio en blanco. Hay que tener cuidado con los valores nulos en las operaciones, ya que <tt>1 * NULL</tt> es igual a <tt>NULL</tt>.</p>
<p><tt>UNIQUE</tt></p>
<p>Evita valores repetidos en una columna, admitiendo valores nulos. Oracle crea un índice automáticamente cuando se habilita esta restricción y lo borra al deshabilitarse.</p>
<p><tt>DEFAULT</tt></p>
<p>Establece un valor por defecto para esa columna, si no se le asigna ninguno.</p>
<p><tt>CHECK</tt></p>
<p>Comprueba que se cumpla una condición determinada al rellenar esa columna. Esta condición sólo debe estar construida con columnas de esta misma tabla.</p>
<p><tt>PRIMARY KEY</tt></p>
<p>Establece el conjunto de columnas que forman la clave primaria de esa tabla. Se comporta como única y obligatoria sin necesidad de explicitarlo. Sólo puede existir una clave primaria por tabla. Puede ser referenciada como clave ajena por otras tablas. Crea un índice automáticamente cuando se habilita o se crea esta restricción. En Oracle, los índices son construidos sobre árboles B<sup>+</sup>.</p>
<p><tt>FOREIGN KEY</tt></p>
<p>Establece que el contenido de esta columna será uno de los valores contenidos en una columna de otra tabla maestra. Esta columna marcada como clave ajena puede ser NULL. No hay límite en el número de claves ajenas. La clave ajena puede ser otra columna de la misma tabla. Se puede forzar que cuando una fila de la tabla maestra sea borrada, todas las filas de la tabla detalle cuya clave ajena coincida con la clave borrada se borren también. Esto se consigue añadiendo la coletilla <tt>ON DELETE CASCADE</tt> en la definición de la clave ajena.</p>
<p>Seguidamente se presenta un ejemplo en el que se crean dos tablas, una de departamentos y otra de empleados:</p>
<pre>REM
REM tabla departamento con un código de departamento, un nombre y una
REM localización.
REM
create table dep (
   cod_dep number(3),
   nombre varchar2(15) not null,
   loc varchar2(10),
   constraint dep_pk primary key (cod_dep),
   constraint dep_loc check
              (loc in ('Valladolid', 'Boecillo', 'Cigales'))
);

REM
REM tabla empleado con un código de empleado, un nombre, un oficio, un
REM jefe, una fecha de alta en la empresa, un salario mensual, una
REM comisión y el código del departamento donde trabaja.
REM
create table emp (
   cod_emp number(3),
   nombre varchar2(10) not null,
   oficio varchar2(11),
   jefe number(3),
   fecha_alta date,
   salario number(10),
   comision number(10),
   cod_dep number(3),
   constraint emp_pk primary key (cod_emp),
   constraint emp_fk foreign key (cod_dep) references dep(cod_dep)
              on delete cascade,
   constraint emp_ck check (salario &#62; 0)
);
 </pre>
<p><strong>4.3 Comando </strong><tt><strong>Describe</strong></tt><strong> </strong></p>
<p>Oracle nos proporciona un comando que resulta muy útil cuando queremos conocer la estructura de una tabla, las columnas que la forman y su tipo y restricciones. Este comando toma una mayor importancia según nos alejemos del momento de creación de una tabla.</p>
<p>La sintásis es la siguiente</p>
<pre>DESCRIBE tabla</pre>
<p>Y un ejemplo de su utilización se puede ver al describir la definición de las dos tablas creadas antes. Como no es una sentencia SQL no necesita el &#8216;;&#8217; al final. También se puede abreviar como <tt>DESC</tt>.</p>
<pre>SQL&#62; describe dep
 Name                            Null?    Type
 ------------------------------- -------- ----
 COD_DEP                         NOT NULL NUMBER(3)
 NOMBRE                          NOT NULL VARCHAR2(15)
 LOC                                      VARCHAR2(10)

SQL&#62; desc emp
 Name                            Null?    Type
 ------------------------------- -------- ----
 COD_EMP                         NOT NULL NUMBER(4)
 NOMBRE                          NOT NULL VARCHAR2(10)
 OFICIO                                   VARCHAR2(10)
 JEFE                                     NUMBER(4)
 FECHA_ALTA                               DATE
 SALARIO                                  NUMBER(10)
 COMISION                                 NUMBER(10)
 COD_DEP                                  NUMBER(3)

 </pre>
<hr size="2" /><strong>5 Modificación </strong></p>
<hr size="2" />Después de crear una tabla, a veces nos encontramos con que se necesita añadir una columna adicional o modificar la definición de una columna existente. Esta operación se puede realizar con el comando <tt>ALTER TABLE</tt>.</p>
<pre>ALTER TABLE tabla {ADD &#124; MODIFY} ({columna tipoColumna [NOT NULL],}<sup>+</sup>);
 </pre>
<p>Hay que tener en cuenta varios puntos:</p>
<ul>
<li>No es posible disminuir el tamaño de un columna.</li>
<li>En las modificaciones, los tipos anterior y nuevo deben ser compatibles, o la tabla debe estar vacía.</li>
<li>La opción <tt>ADD ... NOT NULL</tt> sólo será posible si la tabla está vacía.</li>
<li>La opción <tt>MODIFY ... NOT NULL</tt> sólo podrá realizarse cuando la tabla no contenga ninguna fila con valor nulo en la columna en cuestión.</li>
</ul>
<p>Por ejemplo la sentencia siguiente añade la fecha de nacimiento a la tabla de empleados.</p>
<pre>SQL&#62; alter table emp add (fecha_nac date not null);
 </pre>
<p>También se puede querer modificar una tabla añadiendo o eliminando restricciones. En este caso el comando a utilizar será</p>
<pre>ALTER TABLE tabla {ADD &#124; DROP} CONSTRAINT restricción;
 </pre>
<hr size="2" /><strong>6 Inserción, Actualización y Borrado </strong></p>
<hr size="2" />Una vez que tenemos definida la estructura de una tabla se pueden insertan los datos, modificarlos o borrarlos de la tabla.</p>
<p>Esta tarea entra dentro de las operaciones que se realizan con el lenguaje DML. Este lenguaje permite manipular los objetos de la base de datos, insertando, modificando y/o borrando el contenido de las tablas. Hay que recordar que estas sentencias no son &#8216;autoconfirmadas&#8217; y requieren de la sentencia <tt>COMMIT</tt> para que sus efectos perduren en el tiempo, o de la sentencia <tt>ROLLBACK</tt> para deshacer los cambios efectuados.</p>
<p>A continuación vamos a estudiar tres de las sentencias DML más comunes.<br />
<strong>6.1 Inserción </strong></p>
<p>El comando que permite insertar filas en las tablas es el siguiente.</p>
<pre>INSERT INTO tabla [({columna,}<sup>*</sup>)] VALUES ({expresión,}<sup>+</sup>);
 </pre>
<p>Sólo especificaremos las columnas donde insertar y su orden cuando no insertemos datos en todas ellas o no lo hagamos en el mismo orden en que definimos la tabla. La asociación columna-valor es posicional. Los valores deben cumplir con los tipos de datos definidos. Los valores de tipo caracter y fecha deben ir encerrados entre comillas simples, (&#8221;).</p>
<p>A continuación se puede ver la inserción de filas en las tablas de ejemplo.</p>
<pre> 
REM insertar filas en la tabla dep
insert into dep values (100,'Administracion','Valladolid');
insert into dep values (200,'I+D','Boecillo');
insert into dep values (300,'Produccion','Cigales');

REM insertar filas en la tabla emp
insert into emp values
       (101,'Cano','Presidente',null,'3-FEB-96',450000,null,100);
insert into emp values
       (102,'Roncal','Director',101,'3-FEB-96',350000,null,100);
insert into emp values
       (103,'Rueda','Secretario',102,'17-MAR-96',175000,null,100);
insert into emp values
       (104,'Martin','Contable',102,'17-MAR-96',235000,null,100);
insert into emp values
       (105,'Sanz','Comercial',101,'17-MAR-96',150000,10,100);
insert into emp values
       (106,'Lopez','Comercial',101,'21-MAR-96',150000,15,100);
insert into emp values
       (201,'Perez','Director',101,'4-JUN-96',350000,null,200);
insert into emp values
       (202,'Sastre','Analista',201,'8-JUN-96',300000,null,200);
insert into emp values
       (203,'Garcia','Programador',202,'8-JUN-96',225000,null,200);
insert into emp values
       (204,'Mateo','Programador',202,'8-JUN-96',200000,null,200);
insert into emp values
       (301,'Yuste','Director',101,'3-OCT-96',350000,null,300);
insert into emp values
       (302,'Recio','Analista',301,'4-FEB-97',300000,null,300);
insert into emp values
       (303,'Garcia','Programador',302,'4-FEB-97',210000,null,300);
insert into emp values
       (304,'Santana','Programador',302,'4-FEB-97',200000,null,300);</pre>
<p><strong>6.2 Actualización </strong></p>
<p>Otra de las operaciones más comunes es la modificación de la información almacenada en las tablas. Para ello se utiliza el comando <tt>UPDATE</tt> cuya sintaxis se muestra a continuación.</p>
<pre>UPDATE tabla SET {columna = expresión,}<sup>+</sup> [WHERE condición];
 </pre>
<p>Se especificará en la cláusula <tt>SET</tt> las columnas que se actualizarán y con qué valores. La cláusula WHERE indica las filas con las que se va a trabajar. Si se omite la actualización afectará a todas las filas de la tabla.<br />
<strong>6.3 Borrado </strong></p>
<p>Con insertar y modificar, la otra operación que completa el trio es la de borrado de filas. La sintaxis es la que sigue:</p>
<pre>DELETE FROM tabla [WHERE condición];
 </pre>
<p>Borrará todas las filas que cumplan la condición especificada en la cláusula <tt>WHERE</tt>. Si esta cláusula no se fija, se borrarán todas las filas de la tabla. Aquí cabe decir que aunque con <tt>DELETE</tt> borremos todas las filas de una tabla, no borramos la definición de la tabla del diccionario y podemos insertar datos posteriormente en la tabla. Esta es una diferencia con la sentencia <tt>DROP TABLE</tt>, que produce la eliminación tanto del contenido de la tabla como de la definición de la misma.</p>
<p><strong>7 Selección </strong></p>
<hr size="2" />La recuperación de los datos en el lenguaje SQL se realiza mediante la sentencia <tt>SELECT</tt>, seleccionar. Esta sentencia permite indicar al SGBD la información que se quiere recuperar. Esta es la sentencia SQL, con diferencia, más habitual. La sentencia <tt>SELECT</tt> consta de cuatro partes básicas:</p>
<ul>
<li>La cláusula <tt>SELECT</tt> seguida de la descripción de lo que se desea ver, los nombres de las columnas a seleccionar. Esta parte es obligatoria.</li>
<li>La cláusula <tt>FROM</tt> seguida de la especificación de las tablas de las que se han de obtener los datos. Esta parte es obligatoria.</li>
<li>La cláusula <tt>WHERE</tt> seguida por un criterio de selección, una condición. Esta parte es opcional.</li>
<li>La cláusula <tt>ORDER BY</tt> seguida por el criterio de ordenación. Esta parte es opcional.</li>
</ul>
<p>Una primera aproximación a la sintaxis de la sentencia <tt>SELECT</tt> puede mostrarnos la siguiente expresión:</p>
<pre>SELECT {* &#124; {columna,}<sup>+</sup>}
FROM {tabla,}<sup>+</sup>
[WHERE condición]
[ORDER BY {expresiónColumna [ASC &#124; DESC],}<sup>+</sup>];
 </pre>
<p>Como una primera utilización de la sentencia <tt>SELECT</tt> podemos utilizarla para ver todas las tablas que tenemos en la base de datos.</p>
<pre>SQL&#62; select table_name from user_tables;

TABLE_NAME
------------------------------
DEP
EMP
 </pre>
<p>Un breve análisis de la sentencia anterior nos permite observar que hemos consultado sobre la columna llamada <tt>table_name</tt> almacenada en la tabla <tt>user_tables</tt>, que es la tabla que guarda la información sobre todas las tablas de cada usuario.<br />
<strong>7.1 Selección de Columnas </strong></p>
<p>Las columnas a seleccionar se enumeran sin más en la cláusula <tt>SELECT</tt>. Si se desea seleccionar todas las columnas de una tabla se puede hacer enumerando a todas las columnas o colocando un asterisco, <tt>*</tt>, en su lugar.</p>
<p>Cuando se consulta una base de datos, los nombres de las columnas se usan como cabeceras de presentación. Si éste resulta demasiado largo, corto o críptico, puede cambiarse con la misma sentencia SQL de consulta, creando un <strong>alias de columna</strong>.</p>
<pre>SQL&#62; select nombre "Departamento", loc "Está en" from dep;

Departamento    Esta en
--------------- ----------
Administracion  Valladolid
I+D             Boecillo
Produccion      Cigales
 </pre>
<p><strong>7.2 Cláusula </strong><tt><strong>FROM</strong></tt><strong> </strong></p>
<p>La cláusula <tt>FROM</tt> define las tablas de las que se van a seleccionar las columnas.</p>
<p>Se puede añadir al nombre de las tablas el usuario propietario de las mismas de la forma <tt>usuario.tabla</tt>. De esta manera podemos distinguir entre las tablas de un usuario y otro. Oracle siempre considera como prefijo el nombre del propietario de las tablas, aunque no se lo indiquemos. De esta forma dos o más usuarios pueden tener tablas que se llamen igual sin que surjan conflictos. Si quisiéramos acceder a las filas de la tabla <tt>dep</tt> del usuario <tt>jperez</tt>, (ademas de tener privilegios de lectura sobre esa tabla) deberíamos escribir la siguiente sentencia SQL:</p>
<pre>SQL&#62; select * from jperez.dep;
 </pre>
<p>También se puede asociar un alias a las tablas para abreviar los nombres de las tablas. Un ejemplo se puede ver en la sentencia SQL siguiente:</p>
<pre>SQL&#62; select d.nombre from dep d;
 </pre>
<p><strong>7.3 Cláusula </strong><tt><strong>WHERE</strong></tt><strong> </strong></p>
<p>Hasta ahora hemos visto como puede utilizarse la sentencia <tt>SELECT</tt> para recuperar todas las columnas o un subconjunto de ellas de una tabla. Pero este efecto afecta a todas las filas de la tabla, a menos que especifiquemos algo más en la cláusula <tt>WHERE</tt>. Es aquí donde debemos proponer la condición que han de cumplir todas las filas para salir en el resultado de la consulta. La complejidad del criterio de búsqueda es prácticamente ilimitada, y en él se pueden conjugar operadores de diversos tipos con funciones de columnas, componiendo expresiones más o menos complejas.</p>
<p><strong>Operadores de Comparación</strong></p>
<table border="1" cellpadding="0" width="90%">
<tbody>
<tr>
<td><strong><em>Operador</em></strong></td>
<td><strong><em>Operación</em></strong></td>
<td><strong><em>Ejemplo</em></strong></td>
</tr>
<tr>
<td>=</td>
<td>Igualdad</td>
<td><tt>select * from emp where cod_dep = 100; </tt></td>
</tr>
<tr>
<td>!=, &#60;&#62;, ^=</td>
<td>Desigualdad</td>
<td><tt>select * from emp where cod_dep != 100; </tt></td>
</tr>
<tr>
<td>&#60;</td>
<td>Menor que</td>
<td><tt>select * from emp where cod_dep &#60; 200; </tt></td>
</tr>
<tr>
<td>&#62;</td>
<td>Mayor que</td>
<td><tt>select * from emp where cod_dep &#62; 200; </tt></td>
</tr>
<tr>
<td>&#60;=</td>
<td>Menor o igual que</td>
<td><tt>select * from emp where cod_dep &#60;= 200; </tt></td>
</tr>
<tr>
<td>&#62;=</td>
<td>Mayor o igual que</td>
<td><tt>select * from emp where cod_dep &#62;= 200; </tt></td>
</tr>
<tr>
<td>in</td>
<td>Igual a cualquiera de los miembros entre paréntesis</td>
<td><tt>select * from emp where cod_dep in (100, 300); </tt></td>
</tr>
<tr>
<td>not in</td>
<td>Distinto a cualquiera de los miembros entre paréntesis</td>
<td><tt>select * from emp where cod_dep not in (200); </tt></td>
</tr>
<tr>
<td>between</td>
<td>Contenido en el rango</td>
<td><tt>select * from emp where cod_emp between 100 and 199; </tt></td>
</tr>
<tr>
<td>not between</td>
<td>Fuera del rango</td>
<td><tt>select * from emp where cod_emp not between 100 and 199; </tt></td>
</tr>
<tr>
<td>like &#8216;_abc%&#8217;</td>
<td>Contiene la cadena &#8216;abc&#8217; a partir del segundo carácter y luego cualquier cadena de caracteres</td>
<td><tt>select * from emp where nombre like 'Ma%'; </tt></td>
</tr>
</tbody>
</table>
<p><strong>Operadores de Aritméticos</strong></p>
<table border="1" cellpadding="0" width="90%">
<tbody>
<tr>
<td><strong><em>Operador</em></strong></td>
<td><strong><em>Operación</em></strong></td>
<td><strong><em>Ejemplo</em></strong></td>
</tr>
<tr>
<td>+</td>
<td>Suma</td>
<td><tt>select nombre, salario+comision from emp where oficio='VENDEDOR'; </tt></td>
</tr>
<tr>
<td>-</td>
<td>Resta</td>
<td><tt>select nombre from emp where sysdate-fecha_alta &#62; 365; </tt></td>
</tr>
<tr>
<td>*</td>
<td>Producto</td>
<td><tt>select nombre, salario*12 from emp; </tt></td>
</tr>
<tr>
<td>/</td>
<td>División</td>
<td><tt>select nombre, salario/31 from emp; </tt></td>
</tr>
</tbody>
</table>
<p><strong>Operadores de Cadenas de Caracteres</strong></p>
<table border="1" cellpadding="0" width="90%">
<tbody>
<tr>
<td><strong><em>Operador</em></strong></td>
<td><strong><em>Operación</em></strong></td>
<td><strong><em>Ejemplo</em></strong></td>
</tr>
<tr>
<td>&#124;&#124;</td>
<td>Concatenación</td>
<td><tt>select nombre&#124;&#124;oficio from emp; </tt></td>
</tr>
</tbody>
</table>
<p><strong>7.4 Cláusula </strong><tt><strong>ORDER BY</strong></tt><strong> </strong></p>
<p>Se utiliza para especificar el criterio de ordenación de la respuesta a la consulta. Por defecto la ordenación es ascendente, aunque se puede especificar un orden descendente. La ordenación se puede establecer sobre el contenido de columnas o sobre expresiones con columnas. A continuación se puede ver un ejemplo de uso de la cláusula <tt>ORDER BY</tt> en la que quiere obtener un listado de los empleados ordenado de manera descendente por su salario y en caso de igualdad de salario, ordenado ascendentemente por su nombre.</p>
<pre>SQL&#62; select nombre, salario from emp order by salario desc, nombre;

NOMBRE        SALARIO
---------- ----------
Cano           450000
Perez          350000
Roncal         350000
Yuste          350000
Recio          300000
Sastre         300000
Martin         235000
Garcia         225000
Garcia         210000
Mateo          200000
Santana        200000
Rueda          175000
Lopez          150000
Sanz           150000

14 rows selected.
 </pre>
<p><strong>7.5 Cláusula </strong><tt><strong>DISTINCT</strong></tt><strong> </strong></p>
<p>Cuando se realiza una consulta sobre una tabla en la que se extrae información de varias columnas, puede ocurrir que, si no incluimos la/s columna/s que forman la clave principal, obtengamos filas repetidas en la respuesta.</p>
<p>Si este comportamiento no nos resulta satisfactorio podemos utilizar la cláusula <tt>DISTINCT</tt> para eliminar las filas duplicadas obtenidas como respuesta a una consulta.</p>
<p>Podemos ver como funciona en el siguiente ejemplo, en el que preguntamos por los distintos oficios de nuestros empleados.</p>
<pre>SQL&#62; select oficio from emp;
 </pre>
<p>Sin utilizar la cláusula <tt>DISTINCT</tt> obtendremos la siguiente respuesta</p>
<pre>OFICIO
-----------
Presidente
Director
Secretario
Contable
Comercial
Comercial
Director
Analista
Programador
Programador
Director
Analista
Programador
Programador

14 rows selected.
 </pre>
<p>Pero si incluimos la cláusula <tt>DISTINCT</tt> la respuesta varía para adecuarse más a nuestras espectativas.</p>
<pre>SQL&#62; select distinct oficio from emp;

OFICIO
-----------
Analista
Comercial
Contable
Director
Presidente
Programador
Secretario

7 rows selected.
 </pre>
<p><strong>7.6 Funciones </strong></p>
<p>Existen en SQL muchas funciones que pueden complementar el manejo de los datos en las consultas. Se utilizan dentro de las expresiones y actuan con los valores de las columnas, variables o constantes.</p>
<p>Se pueden incluir en las clásulas <tt>SELECT</tt>, <tt>WHERE</tt> y <tt>ORDER BY</tt>.</p>
<p>Pueden anidarse funciones dentro de funciones. Y existe una gran variedad de funciones para cada tipo de datos:</p>
<ul>
<li>aritméticas,</li>
<li>de cadenas de caracteres,</li>
<li>de manejo de fechas,</li>
<li>de conversión,</li>
<li>otras,</li>
<li>de grupo.</li>
</ul>
<p><strong>Funciones Aritméticas</strong></p>
<table border="1" cellpadding="0" width="90%">
<tbody>
<tr>
<td><strong><em>Función</em></strong></td>
<td><strong><em>Cometido</em></strong></td>
<td><strong><em>Ejemplo</em></strong></td>
<td><strong><em>Resultado</em></strong></td>
</tr>
<tr>
<td>ABS(n)</td>
<td>Calcula el valor absoluto de <em>n</em>.</td>
<td><tt>select abs(-15) from dual; </tt></td>
<td>15</td>
</tr>
<tr>
<td>CEIL(n)</td>
<td>Calcula el valor entero inmediatamente superior o igual a <em>n</em>.</td>
<td><tt>select ceil(15.7) from dual; </tt></td>
<td>16</td>
</tr>
<tr>
<td>FLOOR(n)</td>
<td>Calcula el valor entero inmediatamante inferior o igual a <em>n</em>.</td>
<td><tt>select floor(15.7) from dual; </tt></td>
<td>15</td>
</tr>
<tr>
<td>MOD(m,n)</td>
<td>Calcula el resto resultante de dividir <em>m</em> entre <em>n</em>.</td>
<td><tt>select mod(11,4) from dual; </tt></td>
<td>3</td>
</tr>
<tr>
<td>POWER(m,n)</td>
<td>Calcula la potencia <em>n</em>-esima de <em>m</em>.</td>
<td><tt>select power(3,2) from dual;</tt></td>
<td>9</td>
</tr>
<tr>
<td>ROUND(m,n)</td>
<td>Calcula el redondeo de <em>m</em> a <em>n</em> decimales. Si <em>n</em>&#60;0 el redondeo se efectua a por la izquierda del punto decimal.</td>
<td><tt>select round(123.456,1) from dual; </tt></td>
<td>123.5</td>
</tr>
<tr>
<td>SQRT(n)</td>
<td>Calcula la raíz cuadrada de <em>n</em>.</td>
<td><tt>select sqrt(4) from dual; </tt></td>
<td>2</td>
</tr>
<tr>
<td>TRUNC(m,n)</td>
<td>Calcula <em>m</em> truncado a <em>n</em> decimales (<em>n</em> puede ser negativo).</td>
<td><tt>select trunc(123.456,1) from dual; </tt></td>
<td>123.4</td>
</tr>
<tr>
<td>SIGN(n)</td>
<td>Calcula el signo de <em>n</em>, devolviendo -1 si <em>n</em>&#60;0, 0 si <em>n</em>=0 y 1 si <em>n</em>&#62;0.</td>
<td><tt>select sign(-12) from dual; </tt></td>
<td>-1</td>
</tr>
</tbody>
</table>
<p><strong>Funciones de Cadenas de Caracteres</strong></p>
<table border="1" cellpadding="0" width="90%">
<tbody>
<tr>
<td><strong><em>Función</em></strong></td>
<td><strong><em>Cometido</em></strong></td>
<td><strong><em>Ejemplo</em></strong></td>
<td><strong><em>Resultado</em></strong></td>
</tr>
<tr>
<td>CHR(n)</td>
<td>Devuelve el carácter cuyo valor codificado es <em>n</em>.</td>
<td><tt>select chr(65) from dual; </tt></td>
<td>A</td>
</tr>
<tr>
<td>ASCII(cad)</td>
<td>Devuelve el valor ascii de <em>cad</em>.</td>
<td><tt>select ascii('A') from dual; </tt></td>
<td>65</td>
</tr>
<tr>
<td>CONCAT(cad1,cad2)</td>
<td>Devuelve <em>cad1</em> concatenada con <em>cad2</em>. Esta función es esquivalente al operador &#124;&#124;.</td>
<td><tt>select concat(concat(nombre,' es '),oficio) from emp; </tt></td>
<td>Cano es Presidente, etc.</td>
</tr>
<tr>
<td>LOWER(cad)</td>
<td>Devuelve la cadena <em>cad</em> con todas sus letras convertidas a minúsculas.</td>
<td><tt>select lower('MinUsCulAs') from dual; </tt></td>
<td>minusculas</td>
</tr>
<tr>
<td>UPPER(cad)</td>
<td>Devuelve la cadena <em>cad</em> con todas sus letras convertidas a mayúsculas.</td>
<td><tt>select upper('maYuSCulAs') from dual; </tt></td>
<td>MAYUSCULAS</td>
</tr>
<tr>
<td>INITCAP(cad)</td>
<td>Devuelve <em>cad</em> con el primer caracter en mayúsculas.</td>
<td><tt>select initcap('isabel') from dual; </tt></td>
<td>Isabel</td>
</tr>
<tr>
<td>LPAD(cad1,n,cad2)</td>
<td>Devuelve <em>cad1</em> con longitud <em>n</em>, y ajustada a la derecha, rellenando por la izquierda con <em>cad2</em>.</td>
<td><tt>select lpad('P',5,'*') from dual; </tt></td>
<td>****P</td>
</tr>
<tr>
<td>RPAD(cad1,n,cad2)</td>
<td>Devuelve <em>cad1</em> con longitud <em>n</em>, y ajustada a la izquierda, rellenando por la derecha con <em>cad2</em>.</td>
<td><tt>select rpad('P',5,'*') from dual; </tt></td>
<td>P****</td>
</tr>
<tr>
<td>REPLACE(cad,ant,nue)</td>
<td>Devuelve <em>cad</em> en la que cada ocurrencia de la cadena <em>ant</em> ha sido sustituida por la cadena <em>nue</em>.</td>
<td><tt>select replace('digo','i','ie') from dual; </tt></td>
<td>diego</td>
</tr>
<tr>
<td>SUBSTR(cad,m,n)</td>
<td>Devuelve la sudcadena de <em>cad</em> compuesta por <em>n</em> caracteres a partir de la posicion <em>m</em>.</td>
<td><tt>select substr('ABCDEFG',3,2) from dual; </tt></td>
<td>CD</td>
</tr>
<tr>
<td>LENGTH(cad)</td>
<td>Devuelve la longitud de <em>cad</em>.</td>
<td><tt>select length('cadena') from dual; </tt></td>
<td>6</td>
</tr>
</tbody>
</table>
<p><strong>Funciones de Manejo de Fechas</strong></p>
<table border="1" cellpadding="0" width="90%">
<tbody>
<tr>
<td><strong><em>Función</em></strong></td>
<td><strong><em>Cometido</em></strong></td>
<td><strong><em>Ejemplo</em></strong></td>
<td><strong><em>Resultado</em></strong></td>
</tr>
<tr>
<td>SYSDATE</td>
<td>Devuelve la fecha y hora actuales.</td>
<td><tt>select sysdate from dual; </tt></td>
<td>14-MAR-97</td>
</tr>
<tr>
<td>ADD_MONTHS(d,n)</td>
<td>Devuelve la fecha <em>d</em> incrementada en <em>n</em> meses.</td>
<td><tt>select add_months(sysdate,4) from dual; </tt></td>
<td>14-JUL-97</td>
</tr>
<tr>
<td>LAST_DAY(d)</td>
<td>Devuelve la fecha del último día del mes de <em>d</em>.</td>
<td><tt>select last_day(sysdate) from dual; </tt></td>
<td>31-MAR-97</td>
</tr>
<tr>
<td>MONTHS_BETWEEN(d1, d2)</td>
<td>Devuelve la diferencia en meses entre las fechas <em>d1</em> y <em>d2</em>.</td>
<td><tt>select months_between(sysdate,'01-JAN-97') from dual; </tt></td>
<td>2.43409424</td>
</tr>
<tr>
<td>NEXT_DAY(d,cad)</td>
<td>Devuelve la fecha del primer día de la semana <em>cad</em> después de la fecha <em>d</em>.</td>
<td><tt>select next_day(sysdate, 'sunday') from dual; </tt></td>
<td>16-MAR-97</td>
</tr>
</tbody>
</table>
<p><strong>Funciones de Conversión de Tipos</strong></p>
<table border="1" cellpadding="0" width="90%">
<tbody>
<tr>
<td><strong><em>Función</em></strong></td>
<td><strong><em>Cometido</em></strong></td>
<td><strong><em>Ejemplo</em></strong></td>
<td><strong><em>Resultado</em></strong></td>
</tr>
<tr>
<td>TO_NUMBER(cad,fmto)</td>
<td>Convierte la cadena <em>cad</em> a un número, opcionalmente de acuerdo con el formato <em>fmto</em>.</td>
<td><tt>select to_number('12345') from dual; </tt></td>
<td>124345</td>
</tr>
<tr>
<td>TO_CHAR(d, fmto)</td>
<td>Convierte la fecha <em>d</em> a una cadena de caracteres, opcionalmente de acuerdo con el formato <em>fmto</em>.</td>
<td><tt>select to_char(sysdate) from dual; </tt></td>
<td>&#8216;14-MAR-97&#8242;</td>
</tr>
<tr>
<td>TO_DATE(cad,fmto)</td>
<td>Convierte la cadena <em>cad </em>de tipo varchar2 a fecha, opcionalmente de acuerdo con el formato <em>fmto</em>.</td>
<td><tt>select to_date('1-JAN-97') from dual; </tt></td>
<td>01-JAN-97</td>
</tr>
</tbody>
</table>
<p>Con las fechas pueden utilizarse varios formatos. Estos formatos permiten modificar la presentación de una fecha. En la siguiente tabla se presentan algunos formatos de fecha y el resultado que generan.</p>
<p><strong>Máscaras de Formato Numéricas</strong></p>
<table border="1" cellpadding="0" width="90%">
<tbody>
<tr>
<td><strong><em>Formato</em></strong></td>
<td><strong><em>Cometido</em></strong></td>
<td><strong><em>Ejemplo</em></strong></td>
<td><strong><em>Resultado</em></strong></td>
</tr>
<tr>
<td>cc ó scc</td>
<td>Valor del siglo.</td>
<td><tt>select to_char(sysdate,'cc') from dual; </tt></td>
<td>20</td>
</tr>
<tr>
<td>y,yyy ó sy,yyy</td>
<td>Año con coma, con o sin signo.</td>
<td><tt>select to_char(sysdate,'y,yyy') from dual; </tt></td>
<td>1,997</td>
</tr>
<tr>
<td>yyyy ó yyy ó yy ó y</td>
<td>Año sin signo con cuatro, tres, dos o un dígitos.</td>
<td><tt>select to_char(sysdate,'yyyy') from dual; </tt></td>
<td>1997</td>
</tr>
<tr>
<td>q</td>
<td>Trimestre.</td>
<td><tt>select to_char(sysdate,'q') from dual; </tt></td>
<td>1</td>
</tr>
<tr>
<td>ww ó w</td>
<td>Número de la semana del año o del mes.</td>
<td><tt>select to_char(sysdate,'ww') from dual; </tt></td>
<td>11</td>
</tr>
<tr>
<td>mm</td>
<td>Número del mes.</td>
<td><tt>select to_char(sysdate,'mm') from dual; </tt></td>
<td>03</td>
</tr>
<tr>
<td>ddd ó dd ó d</td>
<td>Número del día del año, del mes o de la semana.</td>
<td><tt>select to_char(sysdate,'ddd') from dual; </tt></td>
<td>073</td>
</tr>
<tr>
<td>hh ó hh12 ó hh24</td>
<td>La hora en formato 12h. o 24h.</td>
<td><tt>select to_char(sysdate,'hh') from dual; </tt></td>
<td>12</td>
</tr>
<tr>
<td>mi</td>
<td>Los minutos de la hora.</td>
<td><tt>select to_char(sysdate,'mi') from dual; </tt></td>
<td>15</td>
</tr>
<tr>
<td>ss ó sssss</td>
<td>Los segundos dentro del minuto, o desde las 0 horas.</td>
<td><tt>select to_char(sysdate,'sssss') from dual; </tt></td>
<td>44159</td>
</tr>
</tbody>
</table>
<p><strong>Máscaras de Formato de Caracteres</strong></p>
<table border="1" cellpadding="0" width="90%">
<tbody>
<tr>
<td><strong><em>Formato</em></strong></td>
<td><strong><em>Cometido</em></strong></td>
<td><strong><em>Ejemplo</em></strong></td>
<td><strong><em>Resultado</em></strong></td>
</tr>
<tr>
<td>syear ó year</td>
<td>Año en Inglés</td>
<td><tt>select to_char(sysdate,'syear) from dual; </tt></td>
<td>nineteen ninety-seven</td>
</tr>
<tr>
<td>month o mon</td>
<td>Nombre del mes o su abreviatura de tres letras.</td>
<td><tt>select to_char(sysdate,'month') from dual; </tt></td>
<td>march</td>
</tr>
<tr>
<td>day ó dy</td>
<td>Nombre del día de la semana o su abreviatura de tres letras.</td>
<td><tt>select to_char(sysdate,'day') from dual; </tt></td>
<td>friday</td>
</tr>
<tr>
<td>a.m. ó p.m.</td>
<td>El espacio del día.</td>
<td><tt>select to_char(sysdate,'a.m.') from dual; </tt></td>
<td>p.m.</td>
</tr>
<tr>
<td>b.c. ó a.d.</td>
<td>Indicador del año respecto al del nacimiento de Cristo.</td>
<td><tt>select to_char(sysdate,'b.c.') from dual; </tt></td>
<td>a.d.</td>
</tr>
</tbody>
</table>
<p><strong>Otras Funciones</strong></p>
<table border="1" cellpadding="0" width="90%">
<tbody>
<tr>
<td><strong><em>Función</em></strong></td>
<td><strong><em>Cometido</em></strong></td>
<td><strong><em>Ejemplo</em></strong></td>
<td><strong><em>Resultado</em></strong></td>
</tr>
<tr>
<td>DECODE(var, val1, cod1, val2, cod2, &#8230;, defecto)</td>
<td>Convierte el valor de <em>var</em>, de acuerdo con la codificación.</td>
<td><tt>select decode(oficio, 'Presidente', 'P', 'Director', 'D', 'X') from emp; </tt></td>
<td>P, D, X, &#8230;</td>
</tr>
<tr>
<td>GREATEST(exp1, exp2, &#8230;)</td>
<td>Devuelve el mayor valor de una lista.</td>
<td>sin ejemplo.</td>
<td>sin ejemplo.</td>
</tr>
<tr>
<td>LEAST(cad,fmto)</td>
<td>Devuelve el menor valor de una lista.</td>
<td>sin ejemplo.</td>
<td>sin ejemplo.</td>
</tr>
<tr>
<td>NVL(val, exp)</td>
<td>Devuelve la expresión exp si <em>val</em> es NULL, y <em>val</em> si en otro caso.</td>
<td><tt>select salario+nvl(comision,0) from emp; </tt></td>
<td>450000, 350000, &#8230;</td>
</tr>
</tbody>
</table>
<p><strong>7.7 Cláusula </strong><tt><strong>GROUP BY</strong></tt><strong> </strong></p>
<p>SQL nos permite agrupar las filas resultado de una consulta en conjuntos y aplicar funciones sobre esos conjuntos de filas.</p>
<p>La sintaxis es la siguiente:</p>
<pre>SELECT {* &#124; {columna,}<sup>+</sup>}
FROM {tabla,}<sup>+</sup>
WHERE condición
GROUP BY {columna ,}<sup>+</sup>
HAVING condición
ORDER BY {expresiónColumna [ASC &#124; DESC],}<sup>+</sup>;
 </pre>
<p>En la cláusula <tt>GROUP BY</tt> se colocan las columnas por las que vamos a agrupar. Y en la cláusula <tt>HAVING</tt> se especifica la condición que han de cumplir los grupos para pasar al resultado.</p>
<p>La evaluación de las diferentes cláusulas en tiempo de ejecución se efectúa en el siguiente orden:</p>
<ul>
<li><tt>WHERE</tt> filtra las filas</li>
<li><tt>GROUP BY</tt> crea una tabla de grupo nueva</li>
<li><tt>HAVING</tt> filtra los grupos</li>
<li><tt>ORDER BY</tt> clasifica la salida</li>
</ul>
<p>Un ejemplo de utilización de la selección de grupos puede ser seleccionar los empleados agrupados por su oficio. Un primer intento de consulta es el siguiente:</p>
<pre>SQL&#62; select nombre, oficio from emp group by oficio;

select nombre, oficio from emp
       *
ERROR at line 1:
ORA-00979: not a GROUP BY expression
 </pre>
<p>Se presenta un error debido a que cuando se utiliza <tt>GROUP BY</tt>, las columnas implicadas en el <tt>SELECT</tt> y que no aparezcan en la cláusula <tt>GROUP BY</tt> deben tener una función de agrupamiento. En otras palabras, la columna <tt>nombre</tt> debe tener una función de agrupamiento que actue sobre ella (max, min, sum, count, avg). Si no puede ser así, deberá llevar dicha columna a la cláusula <tt>GROUP BY</tt>.</p>
<p>De nuevo, el ejemplo quedará así:</p>
<pre>SQL&#62; select count(nombre), oficio from emp group by oficio;

COUNT(NOMBRE) OFICIO
------------- -----------
            2 Analista
            2 Comercial
            1 Contable
            3 Director
            1 Presidente
            4 Programador
            1 Secretario

7 rows selected.
 </pre>
<p>Las funciones de agrupamiento que se pueden utilizar son las siguientes.</p>
<p><strong>Funciones de Agrupamiento</strong></p>
<table border="1" cellpadding="0" width="90%">
<tbody>
<tr>
<td><strong><em>Función</em></strong></td>
<td><strong><em>Cometido</em></strong></td>
<td><strong><em>Ejemplo</em></strong></td>
</tr>
<tr>
<td>COUNT(col)</td>
<td>Cuenta el número de filas agrupadas.</td>
<td><tt>select count(nombre),oficio from emp group by oficio; </tt></td>
</tr>
<tr>
<td>AVG(col)</td>
<td>Calcula el valor medio de todos los valores de la columna <em>col</em>.</td>
<td><tt>select avg(salario),oficio from emp group by oficio; </tt></td>
</tr>
<tr>
<td>MAX(col)</td>
<td>Calcula el valor máximo de todos los valores de la columna <em>col</em>.</td>
<td><tt>select max(salario),oficio from emp group by oficio; </tt></td>
</tr>
<tr>
<td>MIN(col)</td>
<td>Calcula el valor mínimo de todos los valores de la columna <em>col</em>.</td>
<td><tt>select min(salario),oficio from emp group by oficio; </tt></td>
</tr>
<tr>
<td>SUM(col)</td>
<td>Calcula la suma de los valores de la columna <em>col.</em></td>
<td><tt>select sum(salario), oficio from emp group by oficio; </tt></td>
</tr>
<tr>
<td>STDDEV(col)</td>
<td>Calcula la desviación típica de los valores de la columna <em>col </em>sin tener en cuenta los valores nulos.</td>
<td><tt>select stddev(salario), oficio from emp group by oficio; </tt></td>
</tr>
<tr>
<td>VARIANCE(col)</td>
<td>Calcula la varianza de los valores de la columna <em>col</em> sin tener en cuenta los valores nulos.</td>
<td><tt>select variance(salario), oficio from emp group by oficio; </tt></td>
</tr>
</tbody>
</table>
<p>Hay que tener en cuenta que los valores nulos no participan en el cálculo de las funciones de conjuntos. Estas funciones se pueden utilizar con las cláusulas <tt>DISTINCT</tt> y <tt>ALL</tt>. También se pueden utilizar aunque no realicemos agrupación alguna en la consulta, considerando a toda la tabla como un grupo.</p>
<pre>SQL&#62; select count(*) from emp;

  COUNT(*)
----------
        14
 </pre>
<p><strong>7.8 Expresiones con Sentencias </strong><tt><strong>Select</strong></tt><strong> </strong></p>
<p>El resultado de cada consulta es un conjunto de filas. Y con conjuntos se pueden realizar tres operaciones típicas: la unión, la intersección y la diferencia.</p>
<p>Unión, <tt>UNION</tt></p>
<p>Combina todas las filas del primer conjunto con todas las filas del segundo. Cualquier fila duplicada se reducirá a una sóla.</p>
<p>Intersección, <tt>INTERSECT</tt></p>
<p>Examinará las filas de los conjuntos de entrada y devolverá aquellas que aparezcan en ambos. Todas las filas duplicadas serán eliminadas antes de la generación del conjunto resultante.</p>
<p>Diferencia, <tt>MINUS</tt></p>
<p>Devuelve aquellas filas que están en el primer conjunto pero no en el segundo. Las filas duplicadas del primer conjunto se reducirán a una fila única antes de empezar la comparación con el segundo conjunto.</p>
<p><strong>Reglas para el Manejo de los Operadores de Conjuntos: </strong></p>
<ul>
<li>Pueden ser encadenados en cualquier combinación, siendo evaluados de izquierda a derecha.</li>
<li>No existe jerarquía de precedencia en el uso de estos operadores, pero puede ser forzada mediante paréntesis.</li>
<li>Pueden ser empleados con conjuntos de diferentes tablas siempre que se apliquen las siguientes reglas:
<ul>
<li>Las columnas son relacionadas en orden, de izquierda a derecha.</li>
<li>Los nombres de las columnas son irrelevantes.</li>
<li>Los tipos de datos deben coincidir.</li>
</ul>
</li>
</ul>
<p>Como ejemplo podemos consultar sobre todos los nombres de empleado que trabajan para los departamentos 100 o 300. Esto se consigue restando a todos los nombres de empleados, aquellos que están en el departamento 200.</p>
<pre>SQL&#62; select nombre from emp
  2  minus
  3  select nombre from emp where cod_dep=200;

NOMBRE
----------
Cano
Lopez
Martin
Recio
Roncal
Rueda
Santana
Sanz
Yuste

9 rows selected.
 </pre>
<p><strong>7.9 Combinaciones </strong></p>
<p>Hasta ahora hemos construido consultas con una única tabla, pero esto no debe ser siempre así.</p>
<p>De hecho, sólo se alcanza la verdadera potencia del SQL cuando combinamos el contenido de más de una tabla.</p>
<p>Supongamos que queremos conseguir una lista con los empleados y los departamentos para los que trabajan. Esta información está repartida en las dos tablas que tenemos, <tt>emp</tt> y <tt>dep</tt>. Así, podríamos intentar una consulta que seleccionara el campo <tt>nombre</tt> de la tabla <tt>emp</tt> y el <tt>nombre</tt> del departamento. Y aquí surge el primer problema, ¿cómo distinguimos entre dos columnas que llamándose igual, pertenecen a tablas distintas? Para eso se utiliza como prefijo o el nombre de la tabla (<tt>dep.nombre</tt>) o un alias de tabla, un nombre que se asocia a cada tabla y se coloca como prefijo a la columna (<tt>d.nombre</tt>).</p>
<p>Realicemos la consulta &#8230;</p>
<pre>SQL&#62; select e.nombre, d.nombre from emp e, dep d;

NOMBRE     NOMBRE
---------- ---------------
Cano       Administracion
Roncal     Administracion
Rueda      Administracion
Martin     Administracion
Sanz       Administracion
Lopez      Administracion
Perez      Administracion
Sastre     Administracion
Garcia     Administracion
Mateo      Administracion
Yuste      Administracion
Recio      Administracion
Garcia     Administracion
Santana    Administracion
Cano       I+D
Roncal     I+D
Rueda      I+D
...
42 rows selected.
 </pre>
<p>El resultado puede sorprender un poco. Lo que obtenemos es el producto cartesiano de todos los empleados por todos los departamentos. SQL ha cogido cada fila de la tabla <tt>emp</tt> y le ha asociado todos los <tt>cod_dep</tt> de la tabla <tt>dep</tt>.</p>
<p>Para conseguir lo que queremos tenemos que forzar que se asocie a un empleado con el nombre del departamento para el que trabaja. Y esto se puede hacer si añadimos la condición de que el <tt>cod_dep</tt> tenga el mismo valor en la fila de la tabla <tt>emp</tt> que en la fila escogida de la tabla <tt>dep</tt>:</p>
<pre>SQL&#62; select e.nombre, d.nombre from emp e, dep d
  2&#62; where e.cod_dep = d.cod_dep;

NOMBRE     NOMBRE
---------- ---------------
Cano       Administracion
Roncal     Administracion
Rueda      Administracion
Martin     Administracion
Sanz       Administracion
Lopez      Administracion
Perez      I+D
Sastre     I+D
Garcia     I+D
Mateo      I+D
Yuste      Produccion
Recio      Produccion
Garcia     Produccion
Santana    Produccion

14 rows selected.
 </pre>
<p>De la misma manera se pueden combinar más de dos tablas. Lo importante es emparejar los campos que han de tener valores iguales.</p>
<p><strong>Reglas de Combinación: </strong></p>
<ul>
<li>Pueden combinarse tantas tablas como se desee.</li>
<li>El criterio de combinación puede estar formado por más de una pareja de columnas.</li>
<li>En la cláusula <tt>SELECT</tt> pueden citarse columnas de ambas tablas, condicionen o no la combinación.</li>
<li>Si hay columnas con el mismo nombre en las distintas tablas, deben identificarse especificando la tabla de procedencia o utilizando un alias de tabla.</li>
</ul>
<p>Existe un tipo especial de combinación llamada <strong>Combinación Externa</strong>. Suponga que se crea un nuevo departamento, (<tt>insert into dep values (400,'Distribucion','Valladolid');</tt>) pero todavía no hemos asignado personal al mismo. Si realizamos la consulta anterior, el nuevo departamento no aparecerá en la respuesta. Pero esto se puede evitar si señalamos en la cláusula <tt>WHERE</tt> la posibilidad de que en la tabla de empleados no exista alguno de los códigos de departamento que si exista en la tabla de departamentos. Esto se hace colocando un <tt>(+)</tt> de la siguiente manera:</p>
<pre>SQL&#62;  select e.nombre, d.nombre
  2  from emp e, dep d
  3  where e.cod_dep(+)=d.cod_dep;

NOMBRE     NOMBRE
---------- ---------------
Cano       Administracion
Roncal     Administracion
Rueda      Administracion
Martin     Administracion
Sanz       Administracion
Lopez      Administracion
Perez      I+D
Sastre     I+D
Garcia     I+D
Mateo      I+D
Yuste      Produccion
Recio      Produccion
Garcia     Produccion
Santana    Produccion
           Distribucion

15 rows selected.
 </pre>
<p><strong>7.10 Subconsultas </strong></p>
<p>A veces se han de utilizar en una consulta los resultados de otra consulta, llamada subconsulta.</p>
<p>Un ejemplo de esto ocurre cuando queremos conocer los nombres de los empleados cuyo salario está por encima de la media:</p>
<pre>SQL&#62; select nombre from emp
  2  where salario &#62; (select avg(salario) from emp);

NOMBRE
----------
Cano
Roncal
Perez
Sastre
Yuste
Recio

6 rows selected.
 </pre>
<p>La consulta más interna calcula el salario medio, y la consulta más externa lo utiliza para seleccionar los nombres que ganan más que la media.</p>
<p>El valor de comparación puede ser un valor simple, como en el ejemplo anterior, o un conjunto de valores. Hay que tener en cuenta este detalle ya que el tipo de operador a utilizar varía. En el primer caso se puede utilizar un operador de comparación de carácter aritmético (&#60;, &#62;, etc.). Y en el segundo uno de tipo lógico (<tt>IN</tt>).</p>
<p>Las subconsultas pueden devolver más de una columna, y se habrán de comparar de manera consecuente:</p>
<ul>
<li>Las columnas de la clausula <tt>WHERE</tt> de la consulta principal deben estár agrupadas por parentesis.</li>
<li>Las columnas encerradas entre paréntesis deben coincidir en número y tipo de datos con los datos que devuelve la subconsulta.</li>
</ul>
<p>El nivel de anidamiento de subconsultas es ilimitado.</p>
<p>Se puede utilizar una subconsulta para insertar valores en una tabla en el momento de la creación de la misma con la cláusula <tt>AS</tt>. Si quisieramos crear una tabla con los datos de los empleados del departamento 200 lo podríamos hacer de la siguiente manera:</p>
<pre>SQL&#62; create table dep200 (nombre, oficio)
  2  as select nombre,oficio from emp
  3  where cod_dep=200;

Table created.
 </pre>
<p>No es necesario especificar tipos ni tamaños de las columnas, ya que vienen determinados por los tipos y tamaños de las columnas recuperadas en la subconsulta.</p>
<p><strong>8 Eliminación </strong></p>
<hr size="2" />Cuando una tabla ya no es útil y no vamos a volver a necesitarla debe ser borrada. Esta operación se puede realizar con el comando <tt>DROP TABLE</tt>.</p>
<pre>DROP TABLE tabla [CASCADE CONSTRAINTS];
 </pre>
<p>Se borra la tabla de la base de datos, borrando toda la información contenida en la tabla, es decir, todas las filas. También se borrará toda la información que sobre la tabla existiera en el diccionario.</p>
<p>Puede que si alguna columna de esta tabla a borrar sirva como clave ajena de alguna tabla detalle, impida la eliminación de la tabla, ya que existe una restricción que requiere de la existencia de la tabla maestra. Esto se puede areglar colocando la coletilla <tt>CASCADE CONSTRAINTS</tt>. Esto produce que las restricciones de la tabla detalle se borren antes de borrar la tabla maestra.</p>
<p>La siguiente sentencia produce la eliminación de la tabla de departamentos.</p>
<pre>SQL&#62; drop table dep cascade constraints;

Table dropped.
 </pre>
<hr size="2" /><strong>9 Vistas </strong></p>
<hr size="2" />Una vista es como una ventana a través de la cual se puede consultar o cambiar información de la tabla a la que está asociada.</p>
<p>Las vistas tienen la misma estructura que una tabla: filas y columnas. La única diferencia es que sólo se almacena de ellas la definición, no los datos. Los datos que se recuperan mediante una consulta a una vista se presentarán igual que los de una tabla. De hecho, si no se sabe que se está trabajando con una vista, nada hace suponer que es así. Al igual que sucede con una tabla, se pueden insertar, actualizar, borrar y seleccionar datos en una vista. Aunque siempre es posible seleccionar datos de una vista, en algunas condiciones existen restricciones para realizar el resto de las operaciones sobre vistas.</p>
<p><strong>¿Por qué utilizar vistas?</strong></p>
<ul>
<li>Las vistas pueden proporcionar un nivel adicional de seguridad. Por ejemplo, en la tabla de empleados, cada responsable de departamento sólo tendrá acceso a la información de sus empleados. La siguiente sentencia produce la creación de la vista de los empleados del departamento de administración (<tt>cod_dep=100</tt>).</li>
</ul>
<pre>·                 
·                SQL&#62; create view ampAdmin as
·                  2  select * from ep where cod_dep=100;
View created.</pre>
<ul>
<li>Las vistas permiten ocultar la complejidad de los datos. Una BD se compone de muchas tablas. La información de dos o más tablas puede recperarse utilizando una combinación de dos o más tablas, y estas combinaciones pueden llegar a ser muy confusas. Creando una vista como resultado de la combinación se puede ocultar la complejidad al usuario.</li>
</ul>
<ul>
<li>Las vistas ayudan a mantener unos nombres razonables.</li>
</ul>
<p><strong>Creación de una Vista</strong></p>
<pre>CREATE VIEW vista [({columna ,}<sup>+</sup>] AS consulta ;
 </pre>
<p>La vista se crea con las columnas que devuelve una consulta. Si no nos importa que las columnas de la vista hereden los nombres de las columnas recuperadas en la consulta no tenemos que especificarlos.</p>
<p><strong>Borrado de una Vista</strong></p>
<pre>DROP VIEW vista ;
 </pre>
<p><strong>9.1 Operaciones sobre Vistas </strong></p>
<p><strong>Consultas</strong></p>
<p>La consultas sobre las vistas se tratan de igual modo que sobre las tablas.</p>
<p><strong>Actualizaciones</strong></p>
<p>La información puede ser actualizada en las vistas directamente o a través de las tablas sobre las que se definen.</p>
<p>Esisten algunas restricciones:</p>
<p>Borrado de filas de una tabla a través de una vista</p>
<p>La vista se debe crear con filas de una sola tabla; sin utilizar las cláusulas <tt>GROUP BY</tt> y <tt>DISTINCT</tt>; y sin utilizar funciones de grupo o referencias a pseudocolumnas (ROWNUM).</p>
<p>Actualización de filas a través de una vista</p>
<p>La vista ha de estar definida según las restricciones anteriores y además ninguna de las columnas a actualizar debe haber sido definida como una expresión.</p>
<p>Inserción de filas en una tabla a través de una vista</p>
<p>Todas las restricciones y además todas las columnas obligatorias de la tabla asociada deben estar presentes en la vista.<br />
<strong>9.2 Vistas de más de una Tabla </strong></p>
<p>Se pueden definir vistas sobre más de una tabla. Por ejemplo, sobre la combinación de dos tablas.</p>
<p>Podemos querer ver todos los datos de los empleados del departamento Administración.</p>
<pre>SQL&#62; create view depAdmin (cod_emp, nombre_emp, nombre_dep, dir)
  2  as select e.cod_emp, e.nombre, d.nombre, d.loc
  3  from emp e, dep d
  4  where e.cod_dep=d.cod_dep and d.nombre='Administracion';

SQL&#62; select * from depAdmin;

   COD_EMP NOMBRE_EMP NOMBRE_DEP      DIR
---------- ---------- --------------- ----------
       101 Cano       Administracion  Valladolid
       102 Roncal     Administracion  Valladolid
       103 Rueda      Administracion  Valladolid
       104 Martin     Administracion  Valladolid
       105 Sanz       Administracion  Valladolid
       106 Lopez      Administracion  Valladolid

6 rows selected.
 </pre>
<hr size="2" /><strong>10 Jugando con los Nombres </strong></p>
<hr size="2" />A continuación dos comandos que permiten jugar con los nombres de los objetos en SQL: <tt>SINONYM</tt> y <tt>RENAME</tt>.<br />
<strong>10.1 Sinónimos </strong></p>
<p>SQL permite crear un sinónimo para una tabla o vista. Esto supone que pueden utilizarse dos nombres diferentes para un mismo objeto.</p>
<p><strong>Creación de un Sinónimo</strong></p>
<pre>CREATE SYNONYM sinonimo FOR [usuario.]{tabla &#124; vista} ;
 </pre>
<p><strong>Borrado de un Sinónimo</strong></p>
<pre>DROP SYNONYM sinonimo ;
 </pre>
<p>Una primera utilidad de los sinónimos es la posibilidad de independizar las aplicaciones de los nombres físicos de las tablas que manejan. Asi, las aplicaciones harán referencia a un sinónimo de tabla, que en cada caso puede estar asociado a una tabla distinta.</p>
<p>Otra utilidad es la posibilidad de que un usuario acceda a las tablas de otro usuario como si fueran suyas, siempre que tenga permiso para hacerlo, si al definir el sinónimo incluye el nombre del usuario en la denominación de la tabla. Así si el usuarioA tiene permiso para leer el contenido de la tabla <tt>emp</tt> del usuarioB, entonces desde la ejecución de la sentencia <tt>CREATE SYNONYM plantilla FOR usuarioB.emp</tt> verá la tabla <tt>usuarioB.emp</tt> como <tt>plantilla</tt>.<br />
<strong>10.2 Comando </strong><tt><strong>RENAME</strong></tt><strong> </strong></p>
<p>El comando <tt>RENAME</tt> se utiliza para modificar el nombre de una tabla, vista o sinónimo.</p>
<p>La sintásis es la siguiente</p>
<pre>RENAME {tabla &#124; vista &#124; sinonimo} to nuevoNombre ;
 </pre>
<p>Esta sentencia cambiará el nombre antiguo por el nuevo, y a partir de este momento cualquier acceso al objeto por el nombre antiguo será respondido con un mensaje de error.</p>
<p>Conviene resaltar la diferencia entre el comando <tt>SYNONYM</tt> y el comando <tt>RENAME</tt>. Mientras que el primero mantiene el nombre original para acceder al objeto, el segundo elimina ese primer nombre sustituyendolo por el nuevo.</p>
<hr size="2" /><strong>11 Lo Más SQL*Plus </strong></p>
<hr size="2" />En este apartado vamos a profundizar un poco en las otras posibilidades que nos brinda SQL*Plus en los:</p>
<ul>
<li>ficheros de comandos, y</li>
<li>generación de informes,</li>
</ul>
<p><strong>11.1 Ficheros de Comandos </strong></p>
<p>Aunque ya vimos una introducción a los ficheros de comandos en anteriormente, vamos ahora a profundizar un poco en las posibilidades que nos ofrece SQL*Plus.</p>
<p>En un fichero de comandos se pueden incluir:</p>
<ul>
<li>líneas de comentarios,</li>
<li>líneas de ejecución,</li>
<li>líneas de comandos SQL, y</li>
<li>líneas de comandos SQL*Plus.</li>
</ul>
<p><strong>Líneas de Comentarios</strong></p>
<p>Se pueden introducir comentarios en una archivo de comandos de tres maneras:</p>
<ul>
<li>Utilizando del comando <tt>REM</tt> del SQL*Plus.</li>
<li>Utilizando los delimitadores de comentario de SQL <tt>/*</tt> y <tt>*/</tt>.</li>
<li>Utilizando los símbolos de comentario PL/SQL &#8220;<tt>__</tt>&#8220;.</li>
</ul>
<p><strong>Líneas de Ejecución</strong></p>
<p>Constan de una única barra inclinada, &#8220;<tt>/</tt>&#8220;, y se introducen a continuación de cada sentencia SQL indicando su ejecución.</p>
<p>Sustituyen al punto y coma, &#8220;<tt>;</tt>&#8221; al final de las sentencias SQL.</p>
<p><strong>Líneas de Comandos SQL</strong></p>
<p>Se puede introducir cualquiera de los comandos SQL enumerados en este curso, y se ejecutarán de manera secuencial.</p>
<p>Se permite el anidamiento de los ficheros de comandos.</p>
<p><strong>Líneas de Comandos SQL*Plus</strong></p>
<p>SQL*Plus aporta una serie de posibilidades al lenguaje SQL que le acerca un poco mas a lo que entendemos como un lenguaje de programación.</p>
<p>Se pueden definir constantes y variables, capturar datos del teclado, introducir parámetros en la llamada de un archivo de comandos, y alguna cosa más.</p>
<p><strong>Variables de Usuario</strong></p>
<p>Se pueden definir Variables de usuario con el comando <tt>DEFINE</tt></p>
<pre>DEFINE Variable = valor</pre>
<p>Para borrar una variable se utiliza el comando <tt>UNDEFINE</tt></p>
<pre>UNDEFINE variable
 </pre>
<p>Como ejemplo se puede definir la variable <tt>OFICIO</tt></p>
<pre>SQL&#62; define oficio=analista
 </pre>
<p><strong>Variables de Sustitución</strong></p>
<p>Las variables de sustitución son un nombre de variable de usuario con el símbolo <tt>&#38;</tt> delante. Cuando SQL*Plus detecta una variable de sustitución en un comando, ejecuta el comando tomando el valor de la variable.</p>
<p>Esto se puede ver en el ejemplo, donde preguntamos por los empleados que son analistas:</p>
<pre>SQL&#62; define oficio=Analista
SQL&#62; define tabla=emp
SQL&#62; select nombre, oficio from &#38;tabla where oficio='&#38;oficio';
old   1: select nombre, oficio from &#38;tabla where oficio='&#38;oficio'
new   1: select nombre, oficio from emp where oficio='Analista'

NOMBRE     OFICIO
---------- -----------
Sastre     Analista
Recio      Analista
 </pre>
<p><strong>Captura de Datos desde el Terminal </strong></p>
<p>En muchas ocasiones es necesario recoger datos desde un terminal, que luego serán utilizados en el archivo de comandos. Para realizarlo se pueden utilizar dos medios: las variables de sustitución o los parámetros en la línea de comandos.</p>
<p>Cuando SQL*Plus reconoce una variable de sustitución sin valor asignado se lo pide al usuario:</p>
<pre>SQL&#62; select * from dep where nombre='&#38;nombredep';
Enter value for nombredep: I+D
old   1: select * from dep where nombre='&#38;nombredep'
new   1: select * from dep where nombre='I+D'

   COD_DEP NOMBRE          LOC
---------- --------------- ----------
       200 I+D             Boecillo
 </pre>
<p>Si se desea que SQL*Plus pregunte por el valor de la variable al usuario sólo la primera vez que se encuentra con ella, se colocará &#8220;<tt>&#38;&#38;</tt>&#8221; delante de la variable de usuario.</p>
<p>También se pueden utilizar hasta nueve parámetros en la línea de comandos cuando se llama a la ejecución de un archivo de comandos.</p>
<p>En el archivo de comandos nos referiremos a los parámetros con las variables <tt>&#38;1</tt>, <tt>&#38;2</tt>, &#8230; ,<tt>&#38;9</tt> que se corresponden posicionalmente con ellos.</p>
<p>Desde el archivo de comandos se puede hacer referencia a los parámetros cualquier número de veces y en cualquier orden.</p>
<p><strong>Comandos de Comunicación con el Usuario</strong></p>
<p>Los siguientes comandos proporcionan un medio de comunicación con el usuario:</p>
<ul>
<li>PROMPT: presenta un mensaje en la pantalla.</li>
<li>ACCEPT: Solicita un valor y lo almacena en la variable de usuario que se especifíque.</li>
<li>PAUSE: Obliga al usuario a pulsar <em>Return</em> despué de leer un mensaje.</li>
</ul>
<p>Para ver cómo funcionan sirve el siguiente ejemplo:</p>
<pre>prompt Buscar los datos de un empleado.
pause Pulse Return.
accept nombremp prompt 'Empleado? '
select * from emp where nombre='&#38;nombremp';
 </pre>
<p><strong>Otros Comandos</strong></p>
<p>Los siguientes comandos también se pueden incluir en un archivo de comandos:</p>
<ul>
<li>CONNECT: para conectarse como otro usuario.</li>
<li>HELP: para obtener ayuda en línea.</li>
<li>EXIT: para dejar SQL*PLus y salir al Sistema Operativo.</li>
<li>DESCRIBE ó DESC: para obtener información sobre la estructura de una tabla.</li>
<li>HOST o !: para ejecutar un comando del Sistema Operativo.</li>
</ul>
<p><strong>11.2 Generación de Informes </strong></p>
<p>Con SQL*Plus podemos dar forma a los resultados de las consultas para producir un informe. Podremos:</p>
<ul>
<li>Cambiar las cabeceras de las columnas.</li>
<li>Dar forma a las columnas de tipo <tt>number</tt>, <tt>varchar2</tt>, <tt>date</tt> y <tt>long</tt>.</li>
<li>Copiar y listar atributos de presentación de las columnas.</li>
<li>Suprimir valores duplicados e introducir espacios para mejorar la presentación.</li>
<li>Realizar y mostrar cálculos (totales, medias, mínimos, máximos, etc.).</li>
<li>Definir las dimensiones de las páginas.</li>
<li>Ubicar títulos en la cabecera y pie de las páginas.</li>
<li>Introducir la fecha o el número de página en los títulos.</li>
</ul>
<p>Pero de todo esto sólo vamos a ver el modo de realizar las operaciones más comunes y sencillas.</p>
<p>Básicamente, el formato con el que se van a presentar los resultados de las cosultas dependen de unos parámetros y de unos comandos.</p>
<p><strong>Parámetros</strong></p>
<ul>
<li>SET LINESIZE: pone el número máximo de caracteres por línea. Por defecto vale 80 y el máximo es 999.</li>
<li>SET PAGESIZE: pone el número de filas de la salida antes de empezar una nueva página. Por defecto es 25. Incluye el título y las líneas de pausa.</li>
<li>SET HEADING [ON &#124; OFF]: Activa/desactiva la utilización de encabezados de columnas. Por defecto está activado.</li>
<li>SET NULL texto: Indica la cadena de caracteres que hay que colocar en sustitución de los valores NULL. Por defecto es &#8220;&#8221;.</li>
<li>SET ECHO [ON &#124; OFF]: Activa/desactiva la visualización de los comandos que SQL*Plus ejecuta según van siendo tratados. Por defecto está desactivada.</li>
<li>SET FEEDBACK [ n &#124; ON &#124; OFF]: Muestra el número de registros recuperados en cada consulta cuando se recuperan n o más registros. ON se pueden considerar como n=1, y OFF como n=0.</li>
<li>SET VERIFY [ON &#124; OFF]: Controla la salida de confirmación para los valores de las variables de sustitución. Por defecto está activado.</li>
</ul>
<p><strong>Comandos</strong></p>
<ul>
<li>TTITLE: formación del encabezado de página.</li>
<li>BTITLE: formación del pie de página.</li>
<li>COLUMN: formatear cada columna.</li>
<li>BREAK: puntos de ruptura en los listados.</li>
<li>COMPUTE: realizar cálculos con las columnas.</li>
</ul>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[SELECT]]></title>
<link>http://thewaterrat.com/2009/11/14/526/</link>
<pubDate>Sat, 14 Nov 2009 19:39:11 +0000</pubDate>
<dc:creator>Andrea Favale</dc:creator>
<guid>http://thewaterrat.com/2009/11/14/526/</guid>
<description><![CDATA[Would anyone pay for MySpace Music? Pitch yourself, not your idea Blackberry will remain market lead]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://gigaom.com/2009/11/14/would-anyone-pay-for-myspace-music/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+OmMalik+%28GigaOM%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;">Would anyone pay for <strong>MySpace Music</strong>?</span></a><br />
<a href="http://cdixon.org/?p=1893" target="_blank"><span style="color:#b22222;">Pitch <strong>yourself</strong>, not your idea</span></a><br />
<a href="http://gigaom.com/2009/11/13/blackberry-will-remain-market-leader-through-2014-analyst/?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+OmMalik+%28GigaOM%29&#38;utm_content=Netvibes" target="_blank"><span style="color:#b22222;"><strong>Blackberry</strong> will remain market leader</span></a><br />
<a href="http://www.techcrunch.com/2009/11/14/india-rd-hub-silicon-valley/" target="_blank"><span style="color:#b22222;">Can <strong>India</strong> take on Silicon Valley?</span></a><br />
<a href="http://www.techcrunch.com/2009/11/13/makemytrip-com-is-ecommerce-in-india-finally-happening/" target="_blank"><span style="color:#b22222;">An <strong>Entrepreneur</strong> in India</span></a></p>
<p><img class="alignleft size-full wp-image-527" title="India" src="http://thewaterrat.wordpress.com/files/2009/11/india.jpg" alt="India" width="402" height="576" /></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Live Wrestling zum 1. Mal in HD]]></title>
<link>http://tvtimeblog.wordpress.de/2009/11/14/live-wrestling-zum-1-mal-in-hd/</link>
<pubDate>Sat, 14 Nov 2009 10:16:06 +0000</pubDate>
<dc:creator>dirk01</dc:creator>
<guid>http://tvtimeblog.wordpress.de/2009/11/14/live-wrestling-zum-1-mal-in-hd/</guid>
<description><![CDATA[Der Pay-TV Anbieter Sky hat eine ganz besondere Überraschung für alle Wrestlingfreunde parat. Und zw]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><div><img class="size-full wp-image-79" title="wwe-survivor-series" src="http://tvtimeblog.wordpress.com/files/2009/11/wwe-survivor-series.jpg" alt="wwe-survivor-series" width="236" height="140" />Der Pay-TV Anbieter Sky hat eine ganz besondere Überraschung für alle Wrestlingfreunde parat. Und zwar wird die traditionsreiche Wrestlingveranstaltung: WWE Survivor Series nicht nur zum ersteen Mal überhaupt live in HD in Deutschland und Österreich ausgestrahlt, nein, alle Fans, die sich die Liveveranstaltung buchen, können ohne Mehrkosten die Survivor Serie in HD sehen, auch wenn kein HD &#8211; Abo vorliegt.</div>
<div> </div>
<div>Die 23. Auflage dieser Serie, in der alle Profiwrestler von: SmackDown, RAW und ECW auftreten, wird in der Nacht vom: 22.11. auf dem 23.11.09 zu sehen sein. Der Preis für die Liveübertragung und aller Wiederholungen ist allerdings relativ hoch, gerade wenn man bedenkt, das vor allem jüngere Zuschauer diese Events mitverfolgen!  So muss man 15 Euro im Frühbucherrabatt bezahlen (bei Bestellungen bis zum 20. 11. 09, 12.00 Uhr), danach werden es schon stolze 20 Euro sein!</div>
<blockquote>
<div><strong>Unterhalte Dich über dieses Thema mit vielen Anderen in unserem Forum: </strong><a href="http://bigclan.zer-o.eu/index.php?page=Thread&#38;threadID=219"><strong>http://bigclan.zer-o.eu/index.php?page=Thread&#38;threadID=219</strong></a></div>
</blockquote>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Treatments and Clinical Trials for Mesothelioma]]></title>
<link>http://houstonmesotheliomalawyers.wordpress.com/2009/11/14/treatments-and-clinical-trials-for-mesothelioma/</link>
<pubDate>Sat, 14 Nov 2009 00:40:37 +0000</pubDate>
<dc:creator>harry5599</dc:creator>
<guid>http://houstonmesotheliomalawyers.wordpress.com/2009/11/14/treatments-and-clinical-trials-for-mesothelioma/</guid>
<description><![CDATA[For years, chemotherapy has been used for the treatment of tumors to shrink mesothelioma. Recently, ]]></description>
<content:encoded><![CDATA[For years, chemotherapy has been used for the treatment of tumors to shrink mesothelioma. Recently, ]]></content:encoded>
</item>
<item>
<title><![CDATA[Excel und VBA]]></title>
<link>http://interfaceprog.com/2009/11/13/excel-und-vba/</link>
<pubDate>Fri, 13 Nov 2009 11:00:56 +0000</pubDate>
<dc:creator>interfaceprog</dc:creator>
<guid>http://interfaceprog.com/2009/11/13/excel-und-vba/</guid>
<description><![CDATA[Hier habe ich Ihnen ein paar kleine Makros aufgestellt, die Sie vielleicht in Ihrem Alltag mit Excel]]></description>
<content:encoded><![CDATA[Hier habe ich Ihnen ein paar kleine Makros aufgestellt, die Sie vielleicht in Ihrem Alltag mit Excel]]></content:encoded>
</item>
<item>
<title><![CDATA[How to Mimic SQL's SELECT DISTINCT Clause with IBM AS/400's WRKQRY]]></title>
<link>http://arga.wordpress.com/2009/11/13/how-to-mimic-sqls-select-distinct-clause-with-ibm-as-400-s-wrkqry/</link>
<pubDate>Fri, 13 Nov 2009 04:27:52 +0000</pubDate>
<dc:creator>gardine</dc:creator>
<guid>http://arga.wordpress.com/2009/11/13/how-to-mimic-sqls-select-distinct-clause-with-ibm-as-400-s-wrkqry/</guid>
<description><![CDATA[Several days ago, I was stuck with this problem: how do I do a version of SQL&#8217;s SELECT DISTINC]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Several days ago, I was stuck with this problem: how do I do a version of SQL&#8217;s <code>SELECT DISTINCT</code> clause with IBM AS/400&#8217;s (iSeries) <code>WRKQRY</code> command. In other words, how to summarize a field. You see, my user ID on the system is restricted to a menu &#8211; not even given the command-line, in fact &#8211; which is devoid of the ability to run the <code>STRSQL</code> command. After a moment of head-banging, hair-pulling and frantic google searching, here&#8217;s the solution.</p>
<blockquote><p>Define a report break containing [the field you want to distinctly select]. Then in Select Output Type, choose Summary Only. You will only see one occurrance [sic] for each distinct break level. The one downside to this is that Query/400 will insert a blank line in between each row. If you want to print out the data without the blank lines, you can run the output of this query to a temporary file and then query the temporary file seperately.</p>
<p style="text-align:right;"><a href="http://forums.systeminetwork.com/isnetforums/showpost.php?p=34614&#38;postcount=2" target="_blank">Steve Canter</a> on <a href="http://forums.systeminetwork.com/isnetforums/showthread.php?t=10558" target="_blank">SystemiNetwork Forum</a></p>
</blockquote>
<p style="text-align:left;">Thank you,  Steve, for that verbose &#8211; but useful &#8211; explanation. Now, if you let me supplement your explanation with these two screenshots, all will be better, I think.</p>
<p style="text-align:left;">So, let&#8217;s say I have this physical file a.k.a.  table.</p>
<p style="text-align:left;"><a target="_blank" href="http://arga.wordpress.com/files/2009/11/011.jpg"><img class="aligncenter size-medium wp-image-610" title="Sample Physical File with Duplicate Entries in One of the Fields" src="http://arga.wordpress.com/files/2009/11/011.jpg?w=300" border="1" alt="Sample Physical File with Duplicate Entries in One of the Fields" hspace="15" vspace="15" width="300" height="164" /></a></p>
<p style="text-align:left;">As you can see, the file has two fields, Deposit Type Code (<code>SCCODE</code>) and Type Description (<code>PSCDES</code>). Now, let&#8217;s pretend I want to know all distinct values of the first field. With SQL, we&#8217;d use this query: <code>SELECT DISTINCT SCCODE FROM TABLE</code>. This is how you do it with <code>WRKQRY</code>.</p>
<ol>
<li><strong>Do the usual file selections process. </strong>Yadda yadda yadda.</li>
<li><strong>Select the field you want to distinctly select/summarize.</strong> In this case, it&#8217;s SCCODE. <a target="_blank" href="http://arga.wordpress.com/files/2009/11/001.jpg"><img class="aligncenter size-medium wp-image-611" title="001" src="http://arga.wordpress.com/files/2009/11/001.jpg?w=300" border="1" alt="001" hspace="15" vspace="15" width="300" height="168" /></a><a target="_blank" href="http://arga.wordpress.com/files/2009/11/002.jpg"><img class="aligncenter size-medium wp-image-612" title="002" src="http://arga.wordpress.com/files/2009/11/002.jpg?w=300" border="1" alt="002" hspace="15" vspace="15" width="300" height="168" /></a></li>
<li><strong>Define a report break containing [the field you want to distinctly select]. </strong>A report break is basically the list of fields you put on your &#8220;<code>SELECT DISTINCT xxx, yyy</code>&#8221; line. So, if you want to distinctively select two fields, you put two level of breaks here. The iSeries accepts up to six break levels for up to nine fields.<a target="_blank" href="http://arga.wordpress.com/files/2009/11/022.jpg"><img class="aligncenter size-medium wp-image-615" title="02" src="http://arga.wordpress.com/files/2009/11/022.jpg?w=300" border="1" alt="02" hspace="15" vspace="15" width="300" height="168" /></a><a target="_blank" href="http://arga.wordpress.com/files/2009/11/03.jpg"><img class="aligncenter size-medium wp-image-616" title="03" src="http://arga.wordpress.com/files/2009/11/03.jpg?w=300" border="1" alt="03" hspace="15" vspace="15" width="300" height="168" /></a><a target="_blank" href="http://arga.wordpress.com/files/2009/11/041.jpg"><img class="aligncenter size-medium wp-image-621" title="04" src="http://arga.wordpress.com/files/2009/11/041.jpg?w=300" alt="04" width="300" height="168" border="1" vspace="15" hspace="15" /></a><a target="_blank" href="http://arga.wordpress.com/files/2009/11/052.jpg"><img class="aligncenter size-medium wp-image-623" title="05" src="http://arga.wordpress.com/files/2009/11/052.jpg?w=300" border="1" alt="05" hspace="15" vspace="15" width="300" height="168" /></a></li>
<li><strong>Select Output Type, choose Summary Only.<a target="_blank" href="http://arga.wordpress.com/files/2009/11/10.jpg"><img class="aligncenter size-medium wp-image-624" title="10" src="http://arga.wordpress.com/files/2009/11/10.jpg?w=300" border="1" alt="10" hspace="15" vspace="15" width="300" height="168" /></a><a target="_blank" href="http://arga.wordpress.com/files/2009/11/11.jpg"><img class="aligncenter size-medium wp-image-625" title="11" src="http://arga.wordpress.com/files/2009/11/11.jpg?w=300" border="1" alt="11" hspace="15" vspace="15" width="300" height="168" /></a></strong></li>
<li><strong>See the results.</strong> The result should be similar with the faithful <code>SELECT DISTINCT</code> clause, albeit with one blank rows after each item. This can be worked around with saving the result to a database file and running another query and sorting the result field.<a target="_blank" href="http://arga.wordpress.com/files/2009/11/20.jpg"><img class="aligncenter size-medium wp-image-626" title="20" src="http://arga.wordpress.com/files/2009/11/20.jpg?w=300" border="1" alt="20" hspace="15" vspace="15" width="300" height="164" /></a></li>
</ol>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[SELECT]]></title>
<link>http://thewaterrat.com/2009/11/12/select-11/</link>
<pubDate>Thu, 12 Nov 2009 23:08:59 +0000</pubDate>
<dc:creator>Andrea Favale</dc:creator>
<guid>http://thewaterrat.com/2009/11/12/select-11/</guid>
<description><![CDATA[Netflix is the ipod of broadband AP CEO to staff: layoffs will continue Palm Pre sales in substantia]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://gigaom.com/2009/11/12/netflix-is-the-ipod-of-broadband/" target="_blank"><span style="color:#b22222;"><strong>Netflix</strong> is the ipod of broadband</span></a><br />
<a href="http://www.businessinsider.com/ap-prez-to-staff-layoffs-will-continue-2009-11" target="_blank"><span style="color:#b22222;"><strong>AP</strong> CEO to staff: layoffs will continue</span></a><br />
<a href="http://gigaom.com/2009/11/12/palm-pre-sales-in-substantial-decline-analyst/" target="_blank"><span style="color:#b22222;"><strong>Palm Pre</strong> sales in substantial decline analyst</span></a><br />
<a href="http://www.techcrunch.com/2009/11/12/that-1-25-billion-settlement-with-amd-its-about-12-days-of-revenue-for-intel/" target="_blank"><span style="color:#b22222;">That USD 1.25 billion settlement with AMD is about 12 days of revenue for <strong>Intel</strong></span></a><br />
<a href="http://venturebeat.com/2009/11/12/clicker-media-launches-a-programming-guide-for-internet-tv/" target="_blank"><span style="color:#b22222;"><strong>Clicker Media</strong> launches a programming guide for internet tv</span></a></p>
<p><img class="alignleft size-full wp-image-520" title="tv guide" src="http://thewaterrat.wordpress.com/files/2009/11/tv-guide.jpg" alt="tv guide" width="160" height="105" /></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Flex Tree Tips 3: Auto-selecting nodes]]></title>
<link>http://flexbestpractices.wordpress.com/2009/11/12/flex-tree-tips-3-auto-selecting-nodes/</link>
<pubDate>Thu, 12 Nov 2009 17:50:39 +0000</pubDate>
<dc:creator>Pablo Pareja Tobes</dc:creator>
<guid>http://flexbestpractices.wordpress.com/2009/11/12/flex-tree-tips-3-auto-selecting-nodes/</guid>
<description><![CDATA[Working on different projects I have come up to the need of automatically selecting nodes in a tree ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Working on different projects I have come up to the need of automatically selecting nodes in a tree depending on some criteria.<br />
At first, one could think that this can be done through the selectedIndex property of the tree and getItemIndex method, but it is not that simple since this approach would not work properly for cases when one of the node ancestors is closed.<br />
So the solution would just be combining both automatically-opening every ancestor and selecting the node through the property selectedIndex.<br />
Here is an example of how this could be done: (<strong><a href="http://beta.era7.com/era7_software/code/TreeAutoSelectItemSample.swf">link</a> </strong>for the swf)</p>
<pre class="brush: jscript;">
&#38;lt;?xml version=&#38;quot;1.0&#38;quot; encoding=&#38;quot;utf-8&#38;quot;?&#38;gt;
&#38;lt;!--
	 Copyright 2009 Pablo Pareja Tobes

	 This file is part of TreeAutoSelectItemSample

	 TreeAutoSelectItemSample is free software: you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
     the Free Software Foundation, either version 3 of the License, or
     (at your option) any later version.

     TreeAutoSelectItemSample is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with this program.  If not, see &#38;lt;http://www.gnu.org/licenses/&#38;gt;.

--&#38;gt;
&#38;lt;mx:Application xmlns:mx=&#38;quot;http://www.adobe.com/2006/mxml&#38;quot; layout=&#38;quot;absolute&#38;quot; xmlns:ns1=&#38;quot;com.era7.samples.tree.*&#38;quot;&#38;gt;
	&#38;lt;mx:Script&#38;gt;
		&#38;lt;![CDATA[
			import mx.controls.Tree;
			import mx.controls.Alert;

			[Bindable]
			protected var xmlSource:XML = &#38;lt;node id=&#38;quot;1&#38;quot; name=&#38;quot;Node 1&#38;quot;&#38;gt;
												&#38;lt;node name=&#38;quot;Node 2&#38;quot;&#38;gt;
													&#38;lt;node name=&#38;quot;Node 3&#38;quot;/&#38;gt;
													&#38;lt;node name=&#38;quot;A&#38;quot;&#38;gt;
														&#38;lt;node name=&#38;quot;B&#38;quot;/&#38;gt;
														&#38;lt;node name=&#38;quot;C&#38;quot;&#38;gt;
															&#38;lt;node name=&#38;quot;D&#38;quot;/&#38;gt;
														&#38;lt;/node&#38;gt;
													&#38;lt;/node&#38;gt;
												&#38;lt;/node&#38;gt;
												&#38;lt;node name=&#38;quot;Node AB&#38;quot;&#38;gt;
													&#38;lt;node name=&#38;quot;Node ABC&#38;quot;&#38;gt;
														&#38;lt;node name=&#38;quot;Node ABCD&#38;quot;&#38;gt;
															&#38;lt;node name=&#38;quot;Node ABCDE&#38;quot;/&#38;gt;
														&#38;lt;/node&#38;gt;
													&#38;lt;/node&#38;gt;
												&#38;lt;/node&#38;gt;
												&#38;lt;node name=&#38;quot;Node 5&#38;quot;/&#38;gt;
											&#38;lt;/node&#38;gt;;

			private function onSelectButtonClick():void{

				var result:XML = this.xmlSource..node.(@name == nameTextInput.text)[0];
				if(this.xmlSource.@name == nameTextInput.text){
					result = this.xmlSource;
				}

				if(result == null){
					Alert.show(&#38;quot;There is no node with such name&#38;quot;);
				}else{

					var valueParent:XML = result.parent();
	      			var elementsToOpen:Array = new Array();

	      			while(valueParent != null){

		      			if(!tree.isItemOpen(valueParent)){
		      				elementsToOpen.push(valueParent);
		      			}
		      			valueParent = valueParent.parent();
	      			}

	      			for each(var elem:XML in elementsToOpen){
		      			tree.expandItem(elem,true,false);
		      		}

	      			tree.selectedIndex = tree.getItemIndex(result);
	      			tree.validateNow();

	      			tree.scrollToIndex(tree.selectedIndex);
				}
			}

		]]&#38;gt;
	&#38;lt;/mx:Script&#38;gt;

	&#38;lt;mx:Tree id=&#38;quot;tree&#38;quot; width=&#38;quot;500&#38;quot; height=&#38;quot;394&#38;quot; labelField=&#38;quot;@name&#38;quot;
			dataProvider=&#38;quot;{xmlSource}&#38;quot; horizontalCenter=&#38;quot;0&#38;quot; verticalCenter=&#38;quot;0&#38;quot; /&#38;gt;
	&#38;lt;mx:HBox width=&#38;quot;500&#38;quot; backgroundColor=&#38;quot;#E6E6E6&#38;quot; verticalAlign=&#38;quot;middle&#38;quot;
		paddingBottom=&#38;quot;5&#38;quot; paddingLeft=&#38;quot;5&#38;quot; paddingRight=&#38;quot;5&#38;quot; paddingTop=&#38;quot;5&#38;quot; horizontalCenter=&#38;quot;0&#38;quot; verticalCenter=&#38;quot;236&#38;quot;&#38;gt;
		&#38;lt;mx:Label text=&#38;quot;Select item with name:&#38;quot;/&#38;gt;
		&#38;lt;mx:TextInput id=&#38;quot;nameTextInput&#38;quot; text=&#38;quot;D&#38;quot; /&#38;gt;
		&#38;lt;mx:Spacer width=&#38;quot;100%&#38;quot;/&#38;gt;
		&#38;lt;mx:Button label=&#38;quot;Select item!&#38;quot; click=&#38;quot;onSelectButtonClick()&#38;quot;/&#38;gt;
	&#38;lt;/mx:HBox&#38;gt;
&#38;lt;/mx:Application&#38;gt;
</pre>
</div>]]></content:encoded>
</item>

</channel>
</rss>
