sql—存储过程执行循环的多行表输出

68de4m5k  于 2021-07-24  发布在  Java
关注(0)|答案(0)|浏览(185)

这让我不得不把头发拔出来想让它工作。我对存储过程也有点生疏。。
我有一个表,它可以分析数据库中的所有表,并定义它们的数据类型。在这里,我使用这个存储过程来创建具有正确数据类型的表的副本。
目前,它为每个表生成正确的代码,而循环只是不执行代码。看起来这是因为它跨输出表中的几行返回CREATETABLE语句。
如何解决此问题?
输出示例:

示例代码:

DECLARE @command nvarchar(max)
DECLARE @TableName nvarchar(250)
DECLARE @Id INT

DECLARE db_cursorcols CURSOR FOR 
    SELECT DISTINCT [Entity] 
    FROM [dbo].[AttributeProfile]

OPEN db_cursorcols

FETCH NEXT FROM db_cursorcols INTO @TableName

WHILE @@FETCH_STATUS = 0   
BEGIN 
    SET @command = 'WITH A AS (
                                 SELECT TOP 1 
                                     0 AS RowNum, 
                                     ''CREATE TABLE [' + @TableName + 'F] ('' AS [Script] 
                                 FROM [dbo].[AttributeProfile]  
                                 UNION
                                 SELECT 
                                     ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rownum,
                                     ''['' + [Attribute] + ''] '' +
                                     CASE WHEN cur_typename=''varchar'' 
                                        THEN CONCAT(''VARCHAR('',cur_intmaxlen,'') NULL,'')
                                        ELSE cur_typename+'',''
                                     END AS [Script]
--SELECT *
FROM[dbo].[AttributeProfile] 
WHERE [Entity]='''+@TableName+''' 
UNION

SELECT TOP 1 99999999 AS RowNum,'')'' AS [Script] FROM [dbo].[AttributeProfile]

)

SELECT Script FROM A ORDER BY RowNum ASC'
--; INSERT INTO ['+@TableName+'F] SELECT * FROM '+@TableName

print @command
exec sp_executesql @command

    FETCH NEXT FROM db_cursorcols INTO @TableName
END

CLOSE db_cursorcols
DEALLOCATE db_cursorcols

谢谢

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题