I am trying to run a SQL Server 2008 R2 query in Management Studio on Win7.
I need to access 50+ databases with similar names.
But, I got error for a database name :
DECLARE @name1 VARCHAR(16)
SET @name1 = 'HisName_'
DECLARE @whole_name VARCHAR(18)
DECLARE @a_person VARCHAR(2)
DECLARE @a_curosr CURSOR
SET @a_curosr = CURSOR FAST_FORWARD
FOR
SELECT personName FROM @person_names -- @person_names is a table that hold person names
OPEN @a_curosr
FETCH NEXT FROM @a_curosr INTO @a_person
WHILE @@Fetch_Status=0
BEGIN
SET @whole_name = @name1 + @a_person
INSERT INTO [dbo].[mytable]
SELECT a.person_id
FROM [@full_name].[dbo].[myOldTable] as a -- error here, @full_name is Invalid object name
FETCH NEXT FROM @a_curosr INTO @a_person
END
I have created the table with name as [@full_name].[dbo].[myOldTable] hre
, @full_name
is a string , e.g. HisName_
+ a two-letter string.
Why the database name cannot be replaced as a string so that I can access 50+ databases in a loop ?
Thanks