Declaring Table Variable using Existing Table Schema in Sql - sql

I want to declare a Table Variable in my stored procedure using existing tables schema.
I have a Table, say TableA, which has about 30 columns.
I want to declare a Table Variable using the same columns just as we declare a Temporary Table.
For instance,
I can declare a Temporary Table using the schema like this:
SELECT TOP 0 * INTO #Temp_TableA FROM TableA
Can I similarly declare a Table Variable???

From MSDN:
No, table variable is a variable as name suggests so you need to declare it before you can use it like all other T-SQL variables and you need to use INSERT INTO
DECLARE #MyTable TABLE(
ID INT NOT NULL,
Data varchar(30) NOT NULL
);
INSERT INTO #MyTable
SELECT ID, data
From <table>
You can also use a temporary table in your stored procedure. Just add to the beginning of stored procedure this code:
if object_id('tempdb..#TableA') is not null drop table #TableA

You should use a CTE for this purpose:
; with CTE as (SELECT TOP 0* FROM TableA)
SELECT * FROM CTE
The only thing to remember is CTE can only be used in the next line after the initialization. So for example, the following won't work-
; with CTE as (SELECT TOP 0* FROM TableA)
SELECT * FROM TableA
SELECT * FROM CTE
because here CTE will become invalid.

DECLARE A Table Variable having same as SCHEMA of your table first and then INSERT INTO syntax as mentioned by Megatron.
If you are planning to use inside a stored procedure, then use CTE and don't forget to mention ; befire CTE declareation and insert into CTE variable from your table.

Related

storing query outputs dynamically TSQL

I have a loop over different tables which returns results
with different number of columns.
Is it possible to store the output of a query without creating a concrete table?
I've read some posts regarding temporary tables so I tried this simple example:
create table #temp_table1 (id int)
insert into #temp_table1 ('select * from table1')
table1 above could be any table
I get the following error message:
Column name or number of supplied values does not match table definition.
Is there anyway to avoid having hard code table definitions exactly matching the output of your query?
Thanks!
You could do a select into - that will create the temporary table automatically:
SELECT * INTO #Temp
FROM TableName
The problem is that since you are using dynamic SQL , your temporary table will only be available inside the dynamic SQL scope - so doing something like this will result with an error:
EXEC('SELECT * INTO #Temp FROM TableName')
SELECT *
FROM #Temp -- The #Temp table does not exists in this scope!
To do this kind of thing using dynamic SQL you must use a global temporary table (that you must drop once done using!):
EXEC('SELECT * INTO ##GlobalTempFROM TableName')
SELECT * INTO #Temp
FROM ##GlobalTemp -- Since this is a global temporary table you can use it in this scope
DROP TABLE ##GlobalTemp

CTE execute commands before using the CTE Table

Is there a way to write any kind of code before selecting your CTE table ?
DECLARE #TestTable TABLE (ID INT ,name NVARCHAR)
INSERT INTO #TestTable VALUES (1,'a'),(2,'b'),(1,'c')
;WITH TempCte(name)
AS
(
SELECT name FROM #TestTable WHERE ID = 1
)
PRINT 'test'
SELECT * FROM TempCte
No, that cannot be done. If you refer MSDN then :
A common table expression (CTE) 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.
So basically it's the scope of a SINGLE SELECT/ INSERT/ UPDATE/ DELETE/ or CREATE VIEW statement which holds the CTE result set. Anything written after that scope won't be able to access this Temporary data.You can read more here:
http://msdn.microsoft.com/en-us/library/ms175972.aspx

Is it possible to apply SELECT INTO a temporary table from another SELECT?

For some performance improvements, I am looking at using a temporary table rather than a table variable
I am currently putting 100,000s or rows into a table variable using INSERT INTO #table EXECUTE sp_executesql #SQLString (where #SQLString returns a string 'SELECT 'INSERT INTO LiveTable Values('x','y','z') build by dynamic SQL so that the x,y,z values are from the real records)
The INSERT INTO takes a bit of time and I was wondering if, having read about how much better SELECT * INTO #tempTable is, can you do a SELECT * INTO with another SELECT as the source?
So something like
SELECT * INTO #tempTable FROM (SELECT * FROM Table2)
The problem with your query is that all subqueries need a table alias in SQL:
SELECT *
INTO #tempTable
FROM (SELECT * FROM Table2) t;
Short answer is yes (I believe I have done this before, awhile ago, but I don't recall any issues). You can get some more information from this post on msdn:
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/92e5fdf0-e2ad-4f1c-ac35-6ab1c8eec642/select-into-localvarname-from-select-subquery
SELECT * INTO #tempTable FROM (SELECT * FROM Table2)T
SELECT * INTO #tempTable FROM Table2
SELECT * INTO #TempTable
FROM table_name
Yes you can do this, Point to be noted is this #TempTable will be created on the fly, meaning if there is a Temp table that already exists using this error will throw an error as it will try to create a Temp table 1st and then insert the data into it.
To insert data into a table that already exist you will have to use INSERT INTO syntax, something like
INSERT INTO #TempTable --<-- When using this syntax it is best practice to always
SELECT Col1, COl2, .... -- mention the Column names in INSERT INTO and SELECT
FROM TableName -- rather then using SELECT * to makes sure data is being
-- selected from and insert into the RIGHT columns
since you have mentioned you are using it with a stored procedure and would like to use make use of this syntax with store procedure, Im sorry you will not be able to do anything like
SELECT * INTO #Temp Execute usp_Proc
for this you will have to stick with
INSERT INTO #TempTable Execute usp_Proc
The Temp table has to exists before you can insert data into it from a stored Procedure.

Insert into Table select result set from stored procedure but column count is not same

I need something like that which is of course not working.
insert into Table1
(
Id,
Value
)
select Id, value from
(
exec MySPReturning10Columns
)
I wanted to populate Table1 from result set returned by MySPReturning10Columns. Here the SP is returning 10 columns and the table has just 2 columns.
The following way works as long as table and result set from SP have same number of columns but in my case they are not same.
INSERT INTO TableWith2Columns
EXEC usp_MySPReturning2Columns;
Also, I want to avoid adding "." as linked server just to make openquery and openrowset work anyhow.
Is there a way not to have define table strucutre in temp table (all columns with datatypes and lenght)? Something like CTE.
You could use a temporary table as a go-between:
insert into #TempTable exec MySP
insert into Table1 (id, value) select id, value from #TempTable
You could solve the problem in two steps by doing the insert from the stored procedure into a temporary table, then do the insert selecting just the columns you want from the temporary table.
Information on temporary tables: http://www.sqlteam.com/article/temporary-tables
-- Well, declare a temp table or a table var, depending on the number of rows expected
-- from the SP. This table will be basically the result set of your SP.
DECLARE #spResult AS TABLE
(
ID INT,
VALUE FLOAT,
....
);
-- Get the result set of the SP into the temp table.
INSERT #spResult EXEC STORED_PROC;
-- Now you can query the SP's result set for ID and Value;
INSERT Table1 (ID, VALUE)
SELECT ID, VALUE FROM #spResult;
You dont need to create a temporary table, you can do it with single query by creating temporary view like this
with tempView as EXEC MySPReturning10Columns insert into Table1 select id, value from tempView
The temporary view disappears as soon as the statement finishes execution

How can one iterate over stored procedure results from within another stored procedure....without cursors?

I'm not sure if this is something I should do in T-SQL or not, and I'm pretty sure using the word 'iterate' was wrong in this context, since you should never iterate anything in sql. It should be a set based operation, correct? Anyway, here's the scenario:
I have a stored proc that returns many uniqueidentifiers (single column results). These ids are the primary keys of records in a another table. I need to set a flag on all the corresponding records in that table.
How do I do this without the use of cursors? Should be an easy one for you sql gurus!
This may not be the most efficient, but I would create a temp table to hold the results of the stored proc and then use that in a join against the target table. For example:
CREATE TABLE #t (uniqueid int)
INSERT INTO #t EXEC p_YourStoredProc
UPDATE TargetTable
SET a.FlagColumn = 1
FROM TargetTable a JOIN #t b
ON a.uniqueid = b.uniqueid
DROP TABLE #t
You could also change your stored proc to a user-defined function that returns a table with your uniqueidentifiers. You can joing directly to the UDF and treat it like a table which avoids having to create the extra temp table explicitly. Also, you can pass parameters into the function as you're calling it, making this a very flexible solution.
CREATE FUNCTION dbo.udfGetUniqueIDs
()
RETURNS TABLE
AS
RETURN
(
SELECT uniqueid FROM dbo.SomeWhere
)
GO
UPDATE dbo.TargetTable
SET a.FlagColumn = 1
FROM dbo.TargetTable a INNER JOIN dbo.udfGetUniqueIDs() b
ON a.uniqueid = b.uniqueid
Edit:
This will work on SQL Server 2000 and up...
Insert the results of the stored proc into a temporary table and join this to the table you want to update:
INSERT INTO #WorkTable
EXEC usp_WorkResults
UPDATE DataTable
SET Flag = Whatever
FROM DataTable
INNER JOIN #WorkTable
ON DataTable.Ket = #WorkTable.Key
If you upgrade to SQL 2008 then you can pass table parameters I believe. Otherwise, you're stuck with a global temporary table or creating a permanent table that includes a column for some sort of process ID to identify which call to the stored procedure is relevant.
How much room do you have in changing the stored procedure that generates the IDs? You could add code in there to handle it or have a parameter that lets you optionally flag the rows when it is called.
Use temporary tables or a table variable (you are using SS2005).
Although, that's not nest-able - if a stored proc uses that method then you can't dumpt that output into a temp table.
An ugly solution would be to have your procedure return the "next" id each time it is called by using the other table (or some flag on the existing table) to filter out the rows that it has already returned
You can use a temp table or table variable with an additional column:
DECLARE #MyTable TABLE (
Column1 uniqueidentifer,
...,
Checked bit
)
INSERT INTO #MyTable
SELECT [...], 0 FROM MyTable WHERE [...]
DECLARE #Continue bit
SET #Continue = 1
WHILE (#Continue)
BEGIN
SELECT #var1 = Column1,
#var2 = Column2,
...
FROM #MyTable
WHERE Checked = 1
IF #var1 IS NULL
SET #Continue = 0
ELSE
BEGIN
...
UPDATE #MyTable SET Checked = 1 WHERE Column1 = #var1
END
END
Edit: Actually, in your situation a join will be better; the code above is a cursorless iteration, which is overkill for your situation.