2011-12-01 38 views
0

我有一個SQL查詢,我需要插入一個字符串變量,但我收到了錯誤。帶有字符串變量的SQL INSERT查詢

下面是我的SQL INSERT查詢:

Insert into User(Employee, Name, Address, Role, Action) 
Select distinct ur1.Employee, ur1.Name, ur1.Address, ur1.Role, ['%" + action + "%'] as [Action] FROM UserRoles ur1)"; 

string action="insert delete query in database" 

我想插入action到我INSERT發言,但我獲得了大量的語法錯誤。

任何人都可以幫我查詢嗎?

非常感謝您的幫助。

+0

請告訴我們錯誤。如果你不想引擎抱怨,也許你還需要使用'FROM UserRoles ur1''因爲ur1.Employee,...不存在。 – Marco

+0

你想爲這個sql,如果是這樣的話,哪個DBMS(Sql Server,ACcess Oracle等),還是你想要cosde,如果是這樣的話。 –

回答

1
Insert into User(Employee, Name, Address, Role, Action) 
Select distinct ur1.Employee, ur1.Name, ur1.Address, ur1.Role,'insert delete query in database' 
FROM UserRoles ur1; 
+0

'ur1.Employee,... does not exist'查看@Marco的評論 – FosterZ

+0

正如我已經在我的帖子評論中所說的,'ur1'沒有被定義;) – Marco

+0

@Zohalib哇,我沒有知道你的方法可以工作。謝謝! – gymcode

1

字符串拼接的SQL運算符爲||

+0

其實它是|| || –

+0

您好CodeBrikie,你是什麼意思的字符串連接?我需要用'|'代替什麼? – gymcode

+0

@a_horse_with_no_name thx提示。答案調整。 – tobiasbayer

1

你應該嘗試

INSERT INTO User (Employee, Name, Address, Role, Action) 
SELECT DISTINCT ur1.Employee, ur1.Name, 
       ur1.Address, ur1.Role, 
       ['%insert delete query in database%'] 
FROM UserRoles ur1 
1

的一部分,你是你的串聯可變action對腳本的其餘部分看起來像這樣串聯後:

… 
    ['the string value goes here'] as [Action] 
… 

我現在要做一個瘋狂的猜測,但由於方括號的存在,它看起來好像在SQL Server或Sybase上。現在,在這兩種產品中,方括號中的字符序列將被認爲是分隔標識符。使用示例中的括號對[Action]確實有意義,但對於腳本的['...']部分看起來毫無意義。更有可能你的意思是簡單的'...',即沒有方括號,它只是一個字符串常量。

另一個需要注意的事項是:在SQL語句結尾處有一個不匹配的右括號。