Do CTEs use any space in tempdb? - sql-server-2005

Do CTEs use any space in tempdb or does it use memory exclusively?
I've tagged the question with both mssql 2005 and 2008 as I use both.

I'll try not to copy/paste MSDN
It doesn't matter.
A CTE is independent of query execution: it is only a language construct. Think of it as neat derived table or subquery.
This means that except for recursive CTEs (see later), all CTEs can be coded inline. If you use the CTE code once, it is for readability. If you use the CTE twice or more, then it is defensive: you don't want to make a mistake and have the derived table different each use.
Where a CTE is used twice or more, then that code will be executed twice or more. It won't be executed once and cached in tempdb.
Summary: it may or may not, just like if the code was inline.
Note: a recursve CTE is simply a derived table inside a derived table inside a derived table inside a a derived table inside a der... so same applies.
You can see this in Tony Rogerson's article. The use of tempdb would happen anyway if coded inline. He also notes that using a temp table can be better because of the "macro" expansion I explained above
FYI: the same applies to views. Just macros.

A common table expression can be thought of as a temporary result set
that is defined within the execution scope of a single SELECT, INSERT,
UPDATE, DELETE, or CREATE VIEW statement. When the query plan for a
common table expression query uses a spool operator to save
intermediate query results, the Database Engine creates a work table
in tempdb to support this operation.
source

From MSDN: http://msdn.microsoft.com/en-us/library/ms345368.aspx
A common table expression can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement.
When the query plan for a common table expression query uses a spool operator to save intermediate query results, the Database Engine creates a work table in tempdb to support this operation.

Related

Another way of conditioning the query

I saw the block of SQL below in an article in this page:
select #empname = d.Emp_Name
from deleted d
How do you put something like #empname = d.Emp_Name in a SELECT statement?
What does it do? Is it another way of conditioning, instead of using WHERE clause?
Plus, it seems to be in SQL Server, but just to be sure, isn't it something that can be done in MySQL or some other DBMS?
You can assign to a variable this way...
...but this is probably a mistake. This assignment convention is typically used only when you expect exactly one row. However, the deleted table name indicates a likely trigger, and SQL Server will sometimes batch up individual deletions in a single call to the trigger, such that the table has multiple rows. Therefore this trigger is likely not correctly processing some deletions.

How to use an IF statement within a view to drop/use a #Temp Table?

I need to create a view, which begins with the following SQL:
IF OBJECT_ID('tempdb..#TempTable') Is Not null
Drop Table #TempTable
I am also rebuilding this #TempTable further on in the view, and then using data in the Temptable for the rest of the query - for better performance. See:
Reduce cost for Table Valued Function - XML Reader in query plan - how?
However, SSMS is telling me:
Incorrect syntax near the keyword 'IF'
Views or functions are not allowed on temporary tables.
Table names that begin with '#' denote temporary tables.
Is there any way to use the IF statement, drop the Temptable, and then use the rebuilt Temptable in the view?
ANSWER - I need to use a stored procedure, not a view.
A stored procedure is quite different from a view. A view is simply an encapsulated query.
However, a stored procedure cannot be used in a SELECT statement. You can only execute it using EXEC.
What you probably want is a user-defined function (UDF). UDFs return a table, so they can be referenced in the FROM clause of a query. Unlike a view, they can contain multiple statements and can have parameters.
As a note, there is no need to delete temporary tables in stored procedures or functions. If the temporary table is declared in the body of the code, then it is automatically deleted when the code is exited. However, you might want to use a table variable instead.

what kind of statement is SELECT INTO,is it DDL or DML?

there is an specify remark for SELECT INTO clause,that I don't know it?is SELECT INTO a DDL or DML?I will appreciate if explain me that specify remark?
thanks
I would say DML as DDL is used to define the database structure, and DML for managing data.
Select into is not different from a insert into, I belive.
Both. It's DDL because it changes the catalog. It's DML because SELECT is DML.
The Wikipedia article on Data manipulation language says (highlighting is mine):
The SQL-data change statements are a subset of the SQL-data statements; this also contains the SELECT query statement, which strictly speaking is part of the DQL, not the DML. In common practice though, this distinction is not made and SELECT is widely considered to be part of DML, so the DML consists of all SQL-data statements, not only the SQL-data change statements. The SELECT ... INTO ... form combines both selection and manipulation, and thus is strictly considered to be DML because it manipulates (i.e. modifies) data.
I Think Basically Select into is a combination query provided by microsoft from Sql server 2008 onwards to backeup data to a table, here we using DDL for creating table and DML for insertion at the definition level of SELECT INTO.

When to use temporary table in SQL Server 2005

I read about temporary tables, global temporary tables and table variables. I understood it but could not imagine a condition when I have to use this. Please elaborate on when I should use the temporary table.
Most common scenario for using temporary tables is from within a stored procedure.
If there is logic inside a stored procedure which involves manipulation of data that cannot be done within a single query, then in such cases, the output of one query / intermediate results can be stored in a temporary table which then participates in further manipulation via joins etc to achieve the final result.
One common scenario in using temporary tables is to store the results of a SELECT INTO statement
The table variable is relatively new (introduced in SQL Server 2005 - as far as i can remember ) can be used instead of the temp table in most cases. Some differences between the two are discussed here
In a lot of cases, especially in OLTP applications, usage of temporary tables within your procedures means that you MAY possibly have business processing logic in your database and might be a consideration for you to re-look your design - especially in case of n tier systems having a separate business layer in their application.
The main difference between the three is a matter of lifetime and scope.
By a global table, I am assuming you mean a standard, run of the mill, table. Tables are used for storing persistent data. They are accessible to all logged in users. Any changes you make are visible to other users and vice versa.
A temporary table exist solely for storing data within a session. The best time to use temporary tables are when you need to store information within SQL server for use over a number of SQL transactions. Like a normal table, you'll create it, interact with it (insert/update/delete) and when you are done, you'll drop it. There are two differences between a table and a temporary table.
The temporary table is only visible to you. Even if someone else creates a temporary table with the same name, no one else will be able to see or affect your temporary table.
The temporary table exists for as long as you are logged in, unless you explicitly drop it. If you log out or are disconnected SQL Server will automatically clean it up for you. This also means the data is not persistent. If you create a temporary table in one session and log out, it will not be there when you log back in.
A table variable works like any variable within SQL Server. This is used for storing data for use in a single transaction. This is a relatively new feature of TSQL and is generally used for passing data between procedures - like passing an array. There are three differences between a table and a table variable.
Like a temporary table, it is only visible to you.
Because it is a variable, it can be passed around between stored procedures.
The temporary table only exists within the current transaction. Once SQL Server finishes a transaction (with the GO or END TRANSACTION statements) or it goes out of scope, it will be deallocated.
I personally avoid using temporary tables and table variables, for a few reasons. First, the syntax for them is Microsoft specific. If your program is going to interact with more than one RDBMS, don't use them. Also, temporary tables and table variables have a tendency to increase the complexity of some SQL queries. If your code can be accomplished using a simpler method, I'd recommend going with simple.

Using WITH NOLOCK Table Hint in Query Using View - Does it Propagate Within the View?

If a "WITH NOLOCK" query hint is used on a View in SQL Server, does it propagate that hint to the view definition itself, even if NOLOCK is NOT used for the raw tables in the View definition? The reason to need this is that sometimes the support staff wants to do huge time-consuming queries but would rather not force this lock on all queries using the view within the application itself.
Yes, NOLOCK will propagate to the tables used by the view definition (at least in SQL Server 2005).
See Table Hints in MSDN:
In SQL Server 2005, all lock hints are propagated to all the tables and views that are referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.
However,
If a table contains computed columns and the computed columns are computed by expressions or functions accessing columns in other tables, the table hints are not used on those tables. This means the table hints are not propagated. For example, a NOLOCK table hint is specified on a table in the query. This table has computed columns that are computed by a combination of expressions and functions that access columns in another table. The tables referenced by the expressions and functions do not use the NOLOCK table hint when accessed.
If you're using indexed views you might want to read a bit more as there are some special cases there too.
Also see View Resolution for more info.
Just to supplement Rory's excellent answer.
He writes "Yes, NOLOCK will propagate to the tables used by the view definition (at least in SQL Server 2005)."
In fact this will work in SQL 2000 as well.
From BOL:
Because select_statement uses the SELECT statement, it is valid to use and hints as specified in the FROM clause. For more information, see FROM and SELECT.