2015-11-02 136 views
0

我有一個名爲「Union」的數據庫。我試圖在MAINT表中爲這個數據庫執行SQL,但是因爲'union'是一個SQL命令,它會拋出錯誤。我可以從聯合數據庫執行時運行查詢。動態SQL能夠解決我的問題,還是應該更改數據庫名稱?SQL命令名稱是數據庫名稱;使用動態SQL?

我不斷收到不正確的語法附近關鍵字「UNION」這裏是我到目前爲止,

 DECLARE @sql varchar(max) 
DECLARE @Database varchar(5) 
Set @Database = 'UNION' 


SELECT @sql = 'SELECT '[email protected]+' as ''Database'', '[email protected]+'.hsi.useraccount.username as ''User Name'', 
'[email protected]+'.hsi.useraccount.realname as ''Real Name'' 
FROM '[email protected]+'.hsi.useraccount 
WHERE '[email protected]+'.hsi.useraccount.username NOT LIKE ''%deactivated%'' and '[email protected]+'.hsi.useraccount.username not like ''%administrator'' and '[email protected]+'.hsi.useraccount.username not like ''%internal%''' 

execute(@sql) 
+5

用方括號的名稱('[聯盟]') – Siyual

+0

@Siyual:還不如讓他有什麼看法的答案,並得到適當的信貸爲了它。 –

回答

3

添加周圍架構名稱[]支架。

SELECT @sql = REPLACE('SELECT [@Database] as ''Database'', [@Database].hsi.useraccount.username as ''User Name'', 
[@Database].hsi.useraccount.realname as ''Real Name'' 
FROM [@Database].hsi.useraccount 
WHERE [@Database].hsi.useraccount.username NOT LIKE ''%deactivated%'' and [@Database].hsi.useraccount.username not like ''%administrator'' and [@Database].hsi.useraccount.username not like ''%internal%''' 
,'@Database',@Database) 

只要文本「@Database」文本不會在其他地方出現在你的SELECT語句,只是把它變成一個REPLACE()函數,並避免所有嵌入式引號語法和字符串連接頭疼。

+0

感謝這工作! – Scott

0

你也可以改用QUOTENAME手動輸入括號的

declare @db nvarchar(100) 
set @db='performance' 

declare @sql nvarchar(max) 
set @sql='select * from '+QUOTENAME(@db)+'.'+quotename('dbo')+'.'+QUOTENAME('orders') 
print @sql 

exec(@sql)