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???
To declare a table variable, start the DECLARE statement. The name of table variable must start with at(@) sign. The TABLE keyword defines that used variable is a table variable. After the TABLE keyword, define column names and datatypes of the table variable in SQL Server.
A copy of an existing table can be created using a combination of the CREATE TABLE statement and the SELECT statement. The new table has the same column definitions. All columns or specific columns can be selected.
Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With