2013-07-22 20 views
2

我試圖在現有的mdb數據庫中創建新表,但是使用一個變量來指定新的表名,該變量的值從輸入值設置到表單中。如果我爲新表指定名稱,但在使用變量值時失敗,則它工作正常。使用變量名創建新的mdb表

我已經看過幾篇關於使用動態sql但完全不熟悉sql的文章,我一直無法理解這些建議。任何幫助,將不勝感激。

<% 
table1 = Session("tableName") 

set conn = server.CreateObject ("ADODB.Connection") 
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.MapPath ("database.mdb") 

Dim strSQL 

'this works with explict naming and creates a table named table1 
'strSQL = "CREATE TABLE table1 (field1 int, field2 char)" 

'this does not work when trying to use a variable to set the tables name 
strSQL = "CREATE TABLE" & table1 & "(field1 int, field2 char)" 

conn.Execute strSQL 
conn.Close 
%> 
+0

需要'TABLE'後面的空格。 – ZippyV

回答

2

沒有一個實際的錯誤信息,它會很難給出更有用的答案。但是,您的生產代碼中可能存在或可能不存在一個錯誤。您缺少表格名稱周圍的空格,例如:

<% 
table1 = Session("tableName") 

set conn = server.CreateObject ("ADODB.Connection") 
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.MapPath ("database.mdb") 

Dim strSQL 

'this does not work when trying to use a variable to set the tables name 
strSQL = "CREATE TABLE" & table1 & "(field1 int, field2 char)" 

'this should be just fine - note the space after TABLE and before the quote. 
' ditto for the space after the quote and before the open parens 
strSQL = "CREATE TABLE " & table1 & " (field1 int, field2 char)" 

conn.Execute strSQL 
conn.Close 
%> 
+0

謝謝AnonJr和ZippyV--「空間」很好。我期待着一千行不熟悉的sql代碼來解決我的困境。我應該記住他們所說的:「問題越小越難解決」 - 只是增加了空間並按預期工作。 – Clay