Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 [RESOLVED] SQL String Array - How To

Author  Topic 

tmaiden
Yak Posting Veteran

86 Posts

Posted - 2008-01-25 : 10:42:18
Hello All,

I have about 10 different insert into statements which I would like to include into a loop of some sort. Here is what I am trying to accomplish.

SET @aryTableNames = 'thisTable','thatTable','anotherTable'

DO
SELECT * INTO [Server].[dbo].[@aryTableNames]
FROM OPENQUERY(mysqlDB, 'SELECT * FROM `@aryTableNames`')
LOOP

jdaman
Constraint Violating Yak Guru

354 Posts

Posted - 2008-01-25 : 10:59:37
Here is how you would do that in t-sql:
DECLARE @TableNames TABLE ( TableName VARCHAR(30) )

INSERT @TableNames ( TableName )
SELECT 'thisTable' UNION
SELECT 'thatTable' UNION
SELECT 'anotherTable'

DECLARE @sql VARCHAR(100), @Table VARCHAR(30)

WHILE EXISTS ( SELECT TOP 1 * FROM @TableNames )
BEGIN

SELECT @Table = ( SELECT TOP 1 TableName FROM @TableNames )
DELETE FROM @TableNames WHERE TableName = @Table
SELECT @sql = 'SELECT * FROM ['+@Table+']'
EXEC(@sql)

END
Go to Top of Page

tmaiden
Yak Posting Veteran

86 Posts

Posted - 2008-01-25 : 11:53:33
Trying Now; Thanks.
Go to Top of Page

tmaiden
Yak Posting Veteran

86 Posts

Posted - 2008-01-25 : 12:46:00
It worked; here is the code I used.
DECLARE @TableNames TABLE ( TableName VARCHAR(30) )

INSERT @TableNames ( TableName )
SELECT 'thisTable' UNION
SELECT 'thatTable' UNION
SELECT 'anotherTable'

DECLARE @sql VARCHAR(200), @Table VARCHAR(30)

WHILE EXISTS ( SELECT TOP 1 * FROM @TableNames )
BEGIN
SELECT @Table = ( SELECT TOP 1 TableName FROM @TableNames )
DELETE FROM @TableNames WHERE TableName = @Table
SELECT @sql = 'IF EXISTS (SELECT * FROM [dbo].[sysobjects] WHERE id = object_id(N''[dbo].[' + @Table + ']''' + ') AND OBJECTPROPERTY(id, N''IsUserTable'') = 1)' +
' DROP TABLE [dbo].[' + @Table + ']'
EXEC(@sql)
SELECT @sql = 'SELECT * INTO [dbName].[dbo].[' + @Table + '] ' +
'FROM OPENQUERY(mysqlDB, ''SELECT * FROM `' + @Table + '`'')'
EXEC(@sql)
END
Go to Top of Page

jdaman
Constraint Violating Yak Guru

354 Posts

Posted - 2008-01-25 : 13:04:53
Just to be sure:
You drop the table in DB1 then recreate it by selecting from a table with the same name from DB2, right?
Go to Top of Page

tmaiden
Yak Posting Veteran

86 Posts

Posted - 2008-01-25 : 13:14:08
Yeah. I have a mySQL database which I am accessing as a Linked Server. So basically this code is to copy our mySQL database to our SQL Server.
Go to Top of Page
   

- Advertisement -