2016-11-18 82 views
1

這是可能的, 它不工作! 試圖執行執行帶同義詞的SQL動態查詢

Declare @SQL as varchar(1000) 

Set @SQL = 'Select ''create synonym syn_'' + t.name + '' for ['' + 
DB_NAME() + ''].[''+ s.name + ''].['' + t.name + '']'' 

from sys.tables t 
    inner join sys.schemas s 
     on t.schema_id = s.schema_id 
where t.type = ''U'' and t.name in 

(''Episode'',''MasterNPI'',''Patient'',''Enterprises'')' 

Print @SQL 
+0

介意告訴我們什麼,這是實際上是試圖做的,什麼是錯呢? – DForck42

回答

2

你完全搞錯了。您查詢將只執行select查詢,它不會創建synonym

這裏是你在找什麼

DECLARE @SQL AS VARCHAR(1000) 

SET @sql = (SELECT ' create synonym syn_' + t.NAME + ' for ' 
        + Quotename(Db_name()) + '.' + Quotename(s.NAME) 
        + '.' + Quotename(t.NAME) + ' ; ' 
      FROM sys.tables t 
        INNER JOIN sys.schemas s 
          ON t.schema_id = s.schema_id 
      WHERE t.type = 'U' 
        AND t.NAME IN ('Episode', 'MasterNPI', 'Patient', 
            'Enterprises') 
      FOR xml path('')) 

EXEC(@SQL)