Wednesday, March 28, 2012

How to insert data into table varialable in a sp from dynamic table

In my sp,I want to get some data from a table which name is dynamic
,and insert the data to a table varialbe,in other words,look like
below:
StoredProcedure
(
DECLARE @.TABLENAME VARCHAR(255)
DECLARE @.MyTABLE TABLE (ID INT,NAME VARCHAR(255),AGE INT)
INSERT INTO
@.MyTABLE
SELECT
ID,
NAME,
AGE
FROM
@.TABELNAME
)
how to do this?thanksJohn
Well you are goimg to use dynamic sql, try this
declare @.t varchar(10)
set @.t ='Orders'
exec('declare @.table table (col1 int)
insert into @.table select orderid from '+ @.t+'
select * from @.table')
Note ; a declaration of the table variable must be in the scope of the EXEC
command, I'd consider using
sp_executesql system stored procedure
See an example
declare @.sql nvarchar(1000),
@.col sysname,
@.orderid int
select @.col='OrderID', @.orderid=10248
set @.sql = 'select * from Northwind..Orders where '+@.col+'= @.ordid'
exec sp_executesql @.sql, N'@.ordid int',@.orderid
"John Smith" <debussy@.gmail.com> wrote in message
news:1135220972.346999.221580@.o13g2000cwo.googlegroups.com...
> In my sp,I want to get some data from a table which name is dynamic
> ,and insert the data to a table varialbe,in other words,look like
> below:
> StoredProcedure
> (
> DECLARE @.TABLENAME VARCHAR(255)
> DECLARE @.MyTABLE TABLE (ID INT,NAME VARCHAR(255),AGE INT)
> INSERT INTO
> @.MyTABLE
> SELECT
> ID,
> NAME,
> AGE
> FROM
> @.TABELNAME
> )
> how to do this?thanks
>|||I want to returun the table variable as a result set at the end of
stored procedure,your way just insert it to a table variable in a short
scope,can't return to outside,anyway,still need to say thanks to you.
StoredProcedure
(
DECLARE @.TABLENAME VARCHAR(255)
DECLARE @.MyTABLE TABLE (ID INT,NAME VARCHAR(255),AGE INT)
INSERT INTO
@.MyTABLE
SELECT
ID,
NAME,
AGE
FROM
@.TABELNAME
SELECT
ID,
NAME,
AGE
FROM
@.MyTable
)|||I have to use tempoary table to solve this problem

No comments:

Post a Comment