SQL Session – Tips and Tricks for Writing Better Queries
If you're not already a member of the Charlotte SQL Server User Group, go now and sign up. This group is a great resource of knowledge and connections to the SQL Server community in Charlotte, NC. Their plan is to get together once a month and discuss a new and interesting topic on SQL Server.
Joe Webb is a renowned SQL Server expert and former PASS Board Member.
Transact-SQL is not a very difficult language to learn. As long as the syntax is correct, it can be quite forgiving. However to truly get the best performance from your SQL Server, careful consideration should be given to the structure and logic of the queries. In this session, we'll discuss some Transact-SQL tips and tricks that can be employed to help you write better queries, allowing your server to perform better.
Grab a copy of the presentation Joe gave Here.
Good News Everyone!
It's been a while since I've been on here, but I have good reasons.
I've been working at my current employer for three and a half years. I no longer see this place in a positive light. So I've worked hard to find a better job. After a fairly short search I found a new job. It's a really good fit for me. They are a little more structured in technology than where I was. They have higher requirements for those in a client services role. They have a design phase for new work and upgrades. They have a QA process for releasing new code into production, and most importantly, they needed someone with some experience. After less than an hour after leaving the in person interview I got the offer!
I've also spent some time helping a friend's mother with her floors. She wanted to replace the flooring in her kitchen and dining room. She chose to go with laminate faux wood floors. When whe pulled up the old flooring to start, we found beautiful real hard wood floors, one of rooms was even red oak...Talk about SCORE!!!
Those are nothing compared to the last thing that's been taking up time. I've been reading more, and as a result, I'm back into writing. I've finished the 2nd draft of a screenplay that a group of friends and I are planning on shooting in March of next year (or whenever it warms up). I'll be splitting my time between pre-production and all my other obligations for the rest of this year.
I have to say even though this year has had some major crap in it... there have been some very notable plusses. Considering we're coming up on Thanksgiving it was pretty important to get those plusses out there, since I am thankful for them.
Keep an eye on http://hollowcoreproductions.com/ All of my video work will be released through this company.
sp_executesql
I'm pretty sure this is the first time I've brought up dynamically generated SQL statements. But it's time you learn about them. There are times where you'll need to run the same statement against multiple tables. Or agains multiple databases. Sometimes, you may not know how many columns you'll need to create or select during run time. There are many reasons you could use dynamically generated statements, so today, that's what we're coving.
sp_executeSQL
The basis of your dynamically generated statement will be the command sp_executeSQL. It lets you run a string as a SQL statement. All the same rules for T-SQL apply here. Let's look at a simple case:
USE adventureWorks GO DECLARE @sql VARCHAR(1000) SET @sql = 'SELECT TOP 10 * FROM HumanResources.Employee' --now run @sql EXEC sp_execureSQL @sql --you will get the same results by running SELECT TOP 10 * FROM HumanResources.Employee
You could shortcust the EXEC statement by simply calling
USE adventureWorks GO DECLARE @sql VARCHAR(1000) SET @sql = 'SELECT TOP 10 * FROM HumanResources.Employee' EXEC(@sql)
But there is a reason I want you to learn to use sp_executeSQL. What if you wanted to use variables? With EXEC(@sql), you'd have to build some nasty SQL statements. What do I mean by nasty? Well, you'd have to read the variables into the string, that means using CAST or CONVERT to turn the variable datatype into a VARCHAR. That means, you'd have to start using multiple single quotes, and keeping track of how many you've used...
Trust me, you don't want to have to do it that way. Debugging can be a beast.
Instead of that, you can actually include a parameter list as the second variable to the sp_execute SQL command. Check this example out.
USE adventureWorks
GO
DECLARE @IntVariable int
DECLARE @SQLString nvarchar(500)
DECLARE @ParmDefinition nvarchar(500)
/* Build the SQL string one time.*/
SET @SQLString =
N'SELECT BusinessEntityID, NationalIDNumber, JobTitle, LoginID
FROM HumanResources.Employee
WHERE BusinessEntityID = @BusinessEntityID'
/* build the parameter list one time. */
SET @ParmDefinition = N'@BusinessEntityID tinyint'
/* Execute the string with the first parameter value. */
SET @IntVariable = 197
EXEC sp_executesql @SQLString, @ParmDefinition,
@BusinessEntityID = @IntVariable
/* again, this would be the same as running: */
SELECT BusinessEntityID, NationalIDNumber, JobTitle, LoginID
FROM HumanResources.Employee
WHERE BusinessEntityID = 197
In this example, we built a query that accepts one parameter, Business Entity ID. So in order to dynamically call this query, and pass the parameter, we have to define it as a valid parameter. Since the Business Entity is a tiny int, we define that in our second SET statement. Finally, we declare the value in the third SET statement, then EXEC the command.
This is your first step from simple SQL to something more advanced. Once you understand this concept, you can do some really cool things. Want to know how I check for indexes automatically? How about how I check for missing foreign keys? All that and more can be done with dynamic SQL statements.
If you have any questions, please let me know. I'm here to help!
