17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Let’s build an example in the AdventureWorks<strong>2008</strong> database by creating a dummy table to grab<br />

dynamic information out of:<br />

USE AdventureWorks<strong>2008</strong>;<br />

GO<br />

--Create The Table. We’ll pull info from here for our dynamic <strong>SQL</strong><br />

CREATE TABLE Dynamic<strong>SQL</strong>Example<br />

(<br />

TableID int IDENTITY NOT NULL<br />

CONSTRAINT PKDynamic<strong>SQL</strong>Example<br />

PRIMARY KEY,<br />

SchemaName varchar(128) NOT NULL,<br />

TableName varchar(128) NOT NULL<br />

);<br />

GO<br />

/* Populate the table. In this case, We’re grabbing every user<br />

** table object in this database */<br />

INSERT INTO Dynamic<strong>SQL</strong>Example<br />

SELECT s.name AS SchemaName, t.name AS TableName<br />

FROM sys.schemas s<br />

JOIN sys.tables t<br />

ON s.schema_id = t.schema_id;<br />

This should get us a response something like:<br />

(73 row(s) affected)<br />

To quote the old advertising disclaimer: “Actual results may vary.” It’s going to depend on which<br />

examples you’ve already followed along with in the book, which ones you haven’t, and for which ones<br />

you took the initiative and did a DROP on once you were done with them. In any case, don’t sweat it<br />

too much.<br />

OK, so what we now have is a list of all the tables in our current database. Now let’s say that we wanted<br />

to select some data from one of the tables, but we wanted to identify the table only at runtime by using<br />

its ID. For example, I’ll pull out all the data for the table with an ID of 1:<br />

DECLARE @SchemaName varchar(128);<br />

DECLARE @TableName varchar(128);<br />

-- Grab the table name that goes with our ID<br />

SELECT @SchemaName = SchemaName, @TableName = TableName<br />

FROM Dynamic<strong>SQL</strong>Example<br />

WHERE TableID = 25;<br />

-- Finally, pass that value into the EXEC statement<br />

EXEC (‘SELECT * FROM ‘ + @SchemaName + ‘.’ + @TableName);<br />

Chapter 11: Writing Scripts and Batches<br />

345

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

Saved successfully!

Ooh no, something went wrong!