March 12, 2004 at 7:14 am
hi!
i'm trying to get the following script running but keep getting the error saying that i need to declare the @tablename variable in the select statement. any ideas?
declare @value datetime
set @value = CAST('20040129 15:00:00' AS DATETIME)
DECLARE @tablenames TABLE
(
table_id INT IDENTITY,
table_name SYSNAME
)
INSERT INTO @tablenames (table_name)
SELECT name FROM sysobjects
WHERE type='U'
DECLARE @i INT
DECLARE @tablename SYSNAME
SET @i = 1
WHILE (@i <= (SELECT MAX(table_id) FROM @tablenames))
BEGIN
SELECT @tablename = table_name
FROM @tablenames
WHERE table_id = @i
print @tablename
select * from ( @tablename ) where tstamp < @value
SET @i = @i + 1
END
/martin
March 12, 2004 at 7:34 am
Have to use dynamic sql.
Something like
declare @value datetime
set @value = CAST('20040129 15:00:00' AS DATETIME)
DECLARE @tablenames TABLE
(
table_id INT IDENTITY,
table_name SYSNAME
)
INSERT INTO @tablenames (table_name)
SELECT name FROM sysobjects
WHERE type='U'
DECLARE @i INT
DECLARE @tablename SYSNAME
SET @i = 1
WHILE (@i <= (SELECT MAX(table_id) FROM @tablenames))
BEGIN
SELECT @tablename = table_name
FROM @tablenames
WHERE table_id = @i
print @tablename
exec ('select * from ' + @tablename)
SET @i = @i + 1
END
March 12, 2004 at 7:42 am
ok, great! that works perfect. but what about the "where" clause....?
March 12, 2004 at 7:43 am
March 12, 2004 at 7:44 am
Although dynamic sql seem to be a solution, one might be inclined to read this for the pitfalls of that approach. Moreover I would also recommend reading the article on dynamic searches on Erlands' homepage.
--
Frank Kalis
Microsoft SQL Server MVP
Webmaster: http://www.insidesql.org/blogs
My blog: http://www.insidesql.org/blogs/frankkalis/[/url]
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply