What am I doing wrong with my query syntax? - mysql

I am trying to insert a row into my table with the following query in ssms:
INSERT INTO [Reservation].[dbo].[Contacts]
([ContactID]
,[Name]
,[Phone]
,[Email]
,[QoowayUserName])
VALUES
(<"100", nvarchar(50),>
,<"Vincent Chase", nvarchar(50),>
,<"3103331234", nvarchar(50),>
,<"vincent_chase#hollywood.com", nvarchar(50),>
,<"Username", nvarchar(50),>)
GO
I get the error:
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near '<'.
I've also tried using single quotes. What am I doing wrong?

INSERT INTO Reservation.dbo.Contacts
(ContactID
,Name
,Phone
,Email
,QoowayUserName)
VALUES
('100'
,'Vincent Chase'
,'3103331234'
,'vincent_chase#hollywood.com'
,'Username')
You might need to remove the "dbo", like this:
INSERT INTO Reservation.Contacts
(ContactID
,Name
,Phone
,Email
,QoowayUserName)
VALUES
('100'
,'Vincent Chase'
,'3103331234'
,'vincent_chase#hollywood.com'
,'Username')

Related

Coalesce not working in insert statement for a null table

I am trying to use the coalesce function in SQL to avoid getting an error when inserting a row with an auto-incrementing uid into a table that is null. However, the following code is still giving me:
"cannot insert the value null into column 'TABLE_ONE_UID'".
cmdEx.ExecuteNonQuery(
"INSERT INTO TABLE_ONE
(TABLE_ONE_UID, USER_UID, SHT_DATE,
C_S_UID, CST_DATE,
CET_DATE, S_M, PGS)
VALUES ((SELECT MAX(COALESCE(TABLE_ONE_UID, 0)) + 1
FROM TABLE_ONE),
127, '2009-06-15T13:45:30',
0, '2009-06-15T13:45:30','2010-06-15T13:45:30',
'TEST DELETE THIS ROW', 0 )");
The correct way to solve this is with an auto_increment column:
create table PMS_CALC_SCHEDULE (
PMS_CALC_SCHEDULE_UID int auto_increment primary key,
. . .
);
If, for some reason, you want to do the calculation yourself, subject your code to race conditions, and have slower inserts, then you need to do the coalesce in the right place:
INSERT INTO PMS_CALC_SCHEDULE (PMS_CALC_SCHEDULE_UID, . . .)
SELECT COALESCE(MAX(PMS_CALC_SCHEDULE_UID), 0) + 1,
. . .
FROM PMS_CALC_SCHEDULE ;
This would happen when your source table doesn't have any row, MAX would return null in this case.
To prevent this, you can use interchange COALESCE and MAX, e.g.:
INSERT INTO PMS_CALC_SCHEDULE
(PMS_CALC_SCHEDULE_UID, USER_UID, SCHEDULED_DATE,
PMS_CALC_STATUS_UID, CALCULATION_START_DATE,
CALCULATION_END_DATE, STATUS_MESSAGE, PROGRESS)
VALUES ((SELECT COALESCE(MAX(PMS_CALC_SCHEDULE_UID), 0) + 1
FROM PMS_CALC_SCHEDULE),
127, '2009-06-15T13:45:30',
0, '2009-06-15T13:45:30','2010-06-15T13:45:30',
'TEST DELETE THIS ROW', 0 )")
Here's the SQL Fiddle.
If the field is set to AutoIncrement on the table itself, just leave the field out of your Insert-Statement. The value is added by the database itself.

mysql - insert multiple values for single column

I want to insert data into MySQL with multiple values in one field and remaining fields contains only one value.
I have tried below query
INSERT INTO assessment_training(
PARENT_SLNO
RNO
TRAINING_CATEGORY
TRAINING_NAME
)
VALUES (
9,
1,
'Technical',
(1,7)
);
Error #1241
`INSERT INTO assessment_training(PARENT_SLNO,RNO,TRAINING_CATEGORY,TRAINING_NAME) VALUES (9,1,'Technical',(1,7)) Error Code: 1241. Operand should contain 1 column(s)`
You can use CONCAT()
INSERT INTO assessment_training(
PARENT_SLNO,
RNO,
TRAINING_CATEGORY,
TRAINING_NAME
)
VALUES (
9,
1,
'Technical',
CONCAT("1", ",", "7")
);

Subquery with MySql using INSERT

I'm trying to update the database, using a script where the ID of a user isn't readily known, so I'm using a subquery to have mysql find the user id (for the posteruserid value). This is the SQL query i'm using:
INSERT INTO `thread` (`title`, `forumid`, `open`, `replycount`,
`postercount`, `postusername`, `postuserid`, `lastposter`,
`dateline`, `visible`, `keywords`)
SELECT 'IN', 2, 1, 0, 1, 'lemons', `userid` FROM `user`
WHERE `username` = 'lemons', 'lemons', 1375768440, 1, 'IN';
I'm getting a syntax error from the above SQL, and I can't figure out what I'm doing wrong.
EDIT because of the mismatched column name, I tried using an alias, which still doesn't work
INSERT INTO `thread` (`title`, `forumid`, `open`, `replycount`,
`postercount`, `postusername`, `postuserid`, `lastposter`,
`dateline`, `visible`, `keywords`)
SELECT 'IN', 2, 1, 0, 1, 'lemons',
`userid` AS `postuserid` FROM `user` WHERE `username` = 'lemons',
'lemons', 1375768440, 1, 'IN';
column mismatch in insert and select query..column should be same where you are going to insert and from where you are fetching data.
You specify to insert values of 11 columns, but in your SELECT statement, you are providing only 7 values. Please provide the value for lastposter,dateline,visible, and keywords.

Why can't I insert this into MySQL?

I probably made a stupid error on my syntax for the query, but I can't seam to fix it. Here is the query my program tries to execute:
INSERT INTO filez (
filename,
uploadedby,
dateuploaded,
public,
FileSize,
FileTransferSize,
key,
bytes
)
VALUES(
'tacct/tesABCscdsdasdasdD.testtest',
'tacct',
'%27 %December %2012, %7:%32:%15%AM',
1,
7,
7,
'`',
'TestDoc'
)
And here's the mysql_error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key, bytes) VALUES('tacct/tesABCscdsdasdasdD.testtest', 'tacct', '%27 %D' at line 1
I did mysql_real_escape_string() on EVERYTHING except the FileSize and FileTransferSize in the query. Could you tell me what I am doing wrong? Thanks!
The error tells you that the error happens at the text key, and it's quite correct: key is a reserved word in MySQL.
Where you use it as a field name, you must enclose it in backticks (`); it's a good general practice anyway.
So:
INSERT INTO `filez` (
`filename`,
`uploadedby`,
`dateuploaded`,
`public`,
`FileSize`,
`FileTransferSize`,
`key`,
`bytes`
)
VALUES(
'tommy3244/tesABCscdsdasdasdD.testtest',
'tommy3244',
'%27 %December %2012, %7:%32:%15%AM',
1,
7,
7,
'`',
'TestDoc'
)
key is a reserved word and you can not use it in column name without using backtics. try this
INSERT INTO filez (`filename`, `uploadedby`, `dateuploaded`, `public`, `FileSize`, `FileTransferSize`, `key`, `bytes`) VALUES('tommy3244/tesABCscdsdasdasdD.testtest', 'tommy3244', '%27 %December %2012, %7:%32:%15%AM', 1, 7, 7, '`', 'TestDoc')
try using following query
INSERT INTO filez (filename, uploadedby, dateuploaded, public, FileSize, FileTransferSize, `key`, bytes) VALUES
('tommy3244/tesABCscdsdasdasdD.testtest', 'tommy3244', '%27 %December %2012, %7:%32:%15%AM',
1, 7, 7, '`', 'TestDoc')
key is keyword so you have to use backticks as i used above.
For more info check following question too
Select a column with a keyword name
INSERT INTO `filez` (`filename`, `uploadedby`, `dateuploaded`,
`public`, `FileSize`, `FileTransferSize`,
`key`, `bytes`)
VALUES('tommy3244/tesABCscdsdasdasdD.testtest', 'tommy3244',
'%27 %December %2012, %7:%32:%15%AM', 1, 7, 7, '`', 'TestDoc')
ok,
syntax to use near 'key, bytes) both are reserve words, Good practice is always use ` sign for user defined identifiers.
KEY is reserved key word for mysql
try other column name or make backticks like that ``
The issue is key is the reserved keyword of mysql , you can't use it as column name, if you really want then enclose it inside backtick character
key

sql parse full name field into first, middle, last, and suffix

I'm trying to split full names into last, first, middle, and suffix. I searched but couldn't find the exact the same format as mine. I have the following code, but I'm getting this error when running the full select.
Msg 537, Level 16, State 3, Line 1
Invalid length parameter passed to the LEFT or SUBSTRING function.
SpaceComma table gets the correct indexes.
This is the format of the names I have:
CREATE TABLE #myfullnames (fullName VARCHAR(50))
GO
INSERT #myfullnames VALUES ('BROOK SR, JAMES P.')
INSERT #myfullnames VALUES ('BLOCK JR., BILL V.')
INSERT #myfullnames VALUES ('MOOR, CLODE M.')
INSERT #myfullnames VALUES ('SOUDER III, Laurence R.')
INSERT #myfullnames VALUES ('SOUDER, WILL' )
INSERT #myfullnames VALUES ('KOLIV, Kevin E.')
INSERT #myfullnames VALUES ('Simk, JR. Thomas Todd')
INSERT #myfullnames VALUES ('Polio, Gary R.')
I would appreciate your help. Thanks.
select SplitNames.LastName, SplitNames.FirstName,
SplitNames.MiddleName, SplitNames.Title
from (
select [fullName]
, substring([fullName], 1, SpceTitle-1) as LastName
, substring([fullName], SpceMid,(SpceMid - SpceFirstName - 1)) as FirstName
, substring([fullName], SpaceComma.SpceTitle, (SpaceComma.SpceFirstName -
SpaceComma.SpceTitle)) as Title
, nullif(substring([fullName],SpaceComma.SpceMid+1,100),'') as
MiddleName
from (
select [fullName],
charindex(',',[fullName]) as Comma,
charindex(' ',[fullName]+space(1),charindex(',',[fullName])) as
SpceFirstName,
(len([fullName]) + 1 - charindex(' ',reverse([fullName]), 0)) as
SpceMid,
charindex(' ',[fullName], charindex (' ',reverse([fullName]))) as SpceTitle
from #myfullnames
) SpaceComma
) SplitNames
DROP TABLE #myfullnames
The data in your example does not follow any fixed set of rules so there will not be a perfect solution for parsing the names. An example of the rule violation is between "Simk" and "BLOCK" in that the "JR" is inside the comma on one and not the other. The only solution to the rule violation is to manually correct the violators.
We can parse the name using the "PARSENAME" function in SQL Server. SQL Server uses PARSENAME to seperate the SERVERNAME.DATABASE.SCHEMA.TABLE and is limited to four parts.
Here is a query which parses the names
select fullname
, REPLACE(fullname,'.','') AS [1]
, REPLACE(REPLACE(fullname,'.',''),', ','.') AS [2]
, ParseName(REPLACE(REPLACE(fullname,'.',''),', ','.'),2) AS [3]
, REPLACE(ParseName(REPLACE(REPLACE(fullname,'.',''),', ','.'),1),' ','.') AS [4]
, PARSENAME(REPLACE(ParseName(REPLACE(REPLACE(fullname,'.',''),', ','.'),1),' ','.'),1) AS [5]
, PARSENAME(REPLACE(ParseName(REPLACE(REPLACE(fullname,'.',''),', ','.'),1),' ','.'),2) AS [6]
from #myfullnames
The six output columns demonstrate the use of replacing characters with the "." then using PARSENAME to extract a portion of the string.