Tsql。游标中的动态SQL

时间:2018-08-07 00:31:42

标签: sql sql-server-2008 tsql

‌‌‌请,我真的很需要您的帮助! 我想在游标中创建一个动态SQL。 我想用变量@Database替换数据库DB1 我有很多错误。我不知道为什么! ‌‌`

‌declare @SQL NVARCHAR (max)
DECLARE @database NVARCHAR (50) = 'TEST'
--DECLARE c CURSOR FOR 
IF OBJECT_ID('tempdb..#SQL') IS NOT NULL
  DROP TABLE #SQL

 SELECT SQL = 'IF OBJECT_ID('''
  + QUOTENAME(SCHEMA_NAME(o.[schema_id]))
  + '.' + QUOTENAME(o.name) + ''') IS NOT NULL
  BEGIN
   DROP VIEW ' 
   + QUOTENAME(SCHEMA_NAME(o.[schema_id]))
   + '.' + QUOTENAME(o.name) + ';
  END'
  + CHAR(13) + CHAR(10) + 'GO'
  + CHAR(13) + CHAR(10) + Definition 
    into #SQL
FROM [DB1].sys.sql_modules AS s
INNER JOIN [DB1].sys.objects AS o
ON s.[object_id] = o.[object_id]
WHERE o.type_desc = 'VIEW';
DECLARE c CURSOR FOR 
SELECT SQL FROM #SQL

OPEN c

FETCH NEXT FROM c INTO @sql

WHILE @@FETCH_STATUS = 0 
BEGIN
-- SET @sql = REPLACE(@sql,'''','''''')
SET @sql = ' EXEC (''' + REPLACE(REPLACE(@SQL, '''', ''''''), 'GO', '''); EXEC(''') + ''');'

 --'USE [' + @Name + ']; EXEC(''' + @sql + ''')'

 exec (@sql)

 FETCH NEXT FROM c INTO @sql
END     

CLOSE c
DEALLOCATE c

`

2 个答案:

答案 0 :(得分:0)

尝试分两行删除方括号。希望对您有帮助,我的朋友。

FROM DB1.sys.sql_modules AS s 
INNER JOIN DB1.sys.objects AS o

答案 1 :(得分:0)

美好的一天,

请检查以下代码是否满足您的需求:

  

注意!(1)未测试此代码! (2)阅读代码中的注释!

-- Step 1: INSERT into New Table
IF OBJECT_ID('tempdb..#SQL') IS NOT NULL
    DROP TABLE #SQL

SELECT MySQL = '
IF OBJECT_ID(''' + QUOTENAME(SCHEMA_NAME(o.[schema_id])) + '.' + QUOTENAME(o.name) + ''') IS NOT NULL BEGIN
    DROP VIEW ' + QUOTENAME(SCHEMA_NAME(o.[schema_id])) + '.' + QUOTENAME(o.name) + ';
END
GO

' + [definition]
into #SQL
FROM sys.sql_modules AS s
INNER JOIN sys.objects AS o ON s.[object_id] = o.[object_id]
WHERE o.type_desc = 'VIEW';

-- always test each step! If this step seems OK, then we will mark the select as comment
select * from #SQL


-- Step 2: loop through all rows that we inserted to the new table, using CURSOR
DECLARE c CURSOR FOR 
SELECT MySQL FROM #SQL

OPEN c

declare @SQL NVARCHAR (max)
FETCH NEXT FROM c INTO @sql

WHILE @@FETCH_STATUS = 0 BEGIN

    SET @sql = 
        + '------START-----' -- This will help us during the check while we pring the text
        + CHAR(13) + CHAR(10) 
        + 'EXEC (''' + REPLACE(REPLACE(@SQL, '''', ''''''), 'GO', '''); EXEC(''') + ''');'

    -- Again, always check result BEFORE executing it!
    PRINT @sql
    -- If above results are all well and only if you tested them manually, the we can make the PRINT a comment and exeute the query
    --exec (@sql)

    FETCH NEXT FROM c INTO @sql
END     

CLOSE c
DEALLOCATE c