20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Ideally, this first argument is the result you want returned. If it turns out to be NULL, however, then you<br />

want the next argument to be the value that COALESCE() returns:<br />

CONCAT(‘We have no details for ‘,CONCAT(CONCAT(FirstName,’ ‘),LastName))<br />

This argument won’t return NULL so long as FirstName and LastName don’t contain NULL values.<br />

However, if they do, then the final argument you pass is returned, and because the argument is a literal<br />

string, it’s guaranteed to not be NULL:<br />

‘No data available’<br />

You can pass a considerable number of arguments to COALESCE(), though obviously each system has an<br />

upper limit to the number of arguments that can be passed. That limit is fairly high, however.<br />

Using INSERT INTO with<br />

the SELECT Statement<br />

This final section details how a SELECT statement can supply the data to be inserted into a table using<br />

the INSERT INTO statement. Using these two statements in conjunction with one another is useful for<br />

copying data from one table to another. For example, if you decide to restructure a database’s table<br />

design but need to retain all the data, you would use the combination of INSERT INTO and SELECT<br />

statements. You could create your new tables and then use INSERT INTO with SELECT to copy the data<br />

over. The combination is also useful if you want to create a new identical copy of a database — for example,<br />

for backup purposes or if you need to move the database to a new computer.<br />

The basic syntax is as follows:<br />

INSERT INTO destination_table_name<br />

SELECT column_list FROM<br />

source_table_name<br />

WHERE condition<br />

If you use this syntax, the destination columns and source columns must match. The number of columns<br />

and appropriate data types must match, although there’s no need for column names to match. The<br />

WHERE clause is optional and is needed only if you don’t want to copy over all records. For example, if<br />

you want to create a copy of the Location table, first you need to create the table:<br />

CREATE TABLE AnotherLocation<br />

( LocationId int,<br />

Street varchar(50),<br />

City varchar(50),<br />

State varchar(50)<br />

);<br />

After creating the table, you can copy over the data:<br />

INSERT INTO AnotherLocation<br />

SELECT LocationId, Street, City, State<br />

FROM Location<br />

WHERE State IN (‘New State’ ,’Golden State’);<br />

Manipulating Data<br />

185

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!