I have been working with basic SQL for a couple years already. However, only recently I encounter the “WITH” command. From my research, it looks like “WITH” is a method to create a temporary table. But in my experience, you can also use the hash “#” to create a temp table.
I tried to search “WITH” and “#”, but since these are weird search words, I am not getting much result.
Could someone chime me in on what is the difference such as pros and cons for each?
You use
WITHto create a Common Table Expression (CTE). It is not technically a temp table.A temp table is like any other table, but it is stored in
tempdband dropped when the connection is closed.Unlike a temp table, though, a CTE doesn’t actually have a physical store to it. It’s more like a “view”.
Here is a great article on exactly what CTEs are. And unlike temp tables, that persist for the connection, a CTE is:
MSDN Reference on Using Common Table Expressions