sql中while循环的替代解决方案

时间:2016-07-20 04:54:56

标签: sql-server while-loop

如何在不使用while循环的情况下编写以下代码?在这种情况下,有没有其他方法可以避免while循环?

SELECT @count = COUNT(*) from CommonTables

While(@count > 0) 
BEGIN
select top 1 @Sname = Schema_name,@Tname = Name from CommonTables


SET @sql = ''
SET @sql = 'insert into #Temp1 select '''+@Sname+''','''+@Tname+''',column_name,data_type,character_maximum_length FROM '+@DB1+'.information_schema.columns
WHERE table_name = '''+@Tname+''' and TABLE_SCHEMA = '''+@Sname+''''

EXEC SP_EXECUTESQL @SQL

SET @sql = ''
SET @sql = 'insert into #Temp2 select '''+@Sname+''','''+@Tname+''',column_name,data_type,character_maximum_length FROM '+@DB2+'.information_schema.columns
WHERE table_name = '''+@Tname+''' and TABLE_SCHEMA = '''+@Sname+''''

EXEC SP_EXECUTESQL @SQL

DELETE from CommonTables where Name = @Tname and Schema_name = @Sname

SELECT @count = COUNT(*) from CommonTables

END

此处CommonTables包含2个数据库(DB1和DB2)中常见的表列表

1 个答案:

答案 0 :(得分:0)

根本不需要循环。

select  @sql    = isnull(@sql, '')
        + N'INSERT INTO #Temp1 '
        + N'SELECT table_schema, table_name,column_name,data_type,character_maximum_length '
        + N'FROM ' + QUOTENAME(@DB1) + '.INFORMATION_SCHEMA.COLUMNS '
        + N'WHERE table_name = ''' + Name + ''' and TABLE_SCHEMA = ''' + Schema_name + ''';' + char(13)
from    CommonTables

print   @sql
exec    sp_executesql @sql

如果你想要2个DB不需要2个单独的sp_execute语句。您可以组合成一个单独的sp_execute

这是查询

select  @sql    = isnull(@sql, '')
        + N'insert into ' + db.temptbl + ' '
        + N'SELECT TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH '
        + N'FROM ' + QUOTENAME(db.dbname) + '.INFORMATION_SCHEMA.COLUMNS '
        + N'WHERE TABLE_NAME = ''' + Name + ''' AND TABLE_SCHEMA = ''' + Schema_name + ''';' + char(13)
from    CommonTables
        cross join
        (
            select  temptbl = '#Temp1', dbname = 'DB1'  union all
            select  temptbl = '#Temp2', dbname = 'DB2'
        ) db

print   @sql
exec    sp_executesql @sql