简体   繁体   中英

SQL INSERT Query with String variable in it

I have an SQL query in which I need to insert a string variable but I am getting errors from it.

Below is my SQL INSERT query:

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"

I would like to insert string action into my INSERT statement, but I am getting lots of syntax errors.

Can anyone help me with the query?

Thank you in advance for any help.

The SQL operator for string concatenation is || .

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;

You should try

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

The part where you are concatenating your action variable to the rest of the script looks something like this after the concatenation:

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

I'm now going to take a wild guess but it does seem as if you are on SQL Server or on Sybase, because of the square brackets. Now, in either of those two products, the sequences of characters enclosed in square brackets would be considered delimited identifiers . Using the brackets in your example does make sense for [Action] but seems absolutely pointless for the ['...'] part of your script. It is more likely that you meant simply '...' , ie without the square brackets, which simply stands for a string constant.

One other thing to note: there's an unmatched closing parenthesis at the end of your SQL statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM