I received a MySQL data dump and am trying to insert the data into a set of temporary tables. The creation statement for the first table is shown below. When I run this I receive the 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 ''temp_books'( 'ID'int( 11 ) NOT NULL AUTO_INCREMENT, 'start'varchar( 20 ) ' at line 1
«. I’ve checked the documentation for MySQL syntax, and I don’t see that the problem is.
CREATE TABLE 'temp_books' (
'ID' int(11) NOT NULL AUTO_INCREMENT,
'start' varchar(20) NOT NULL,
'customer_id' int(11) NOT NULL DEFAULT '0',
'total_num' int(11) NOT NULL,
'amount' double(5,2) NOT NULL DEFAULT '0.00',
'changed' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ('ID'),
UNIQUE KEY 'start' ('start')
) ENGINE=MyISAM AUTO_INCREMENT=4853 DEFAULT CHARSET=latin1;
asked Jan 18, 2009 at 2:37
You shouldn’t put single-quotes on your identifiers. If you’re going to quote them use the «back tick» character (“`”). You can also use double-quotes but you have to specify that mode:
SET sql_mode='ANSI_QUOTES';
http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
answered Jan 18, 2009 at 3:09
TurnkeyTurnkey
9,2263 gold badges27 silver badges36 bronze badges
I’ve ALWAYS had issues with CREATE TABLE. Not sure why. Takes some trial-and-error.
Try this:
CREATE TABLE temp_books (
ID int(11) NOT NULL AUTO_INCREMENT,
start varchar(20) NOT NULL,
customer_id int(11) NOT NULL DEFAULT '0',
total_num int(11) NOT NULL,
amount double(5,2) NOT NULL DEFAULT '0.00',
changed timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (ID),
UNIQUE KEY start (start)
) ENGINE=MyISAM AUTO_INCREMENT=4853 DEFAULT CHARSET=latin1;
answered Jan 18, 2009 at 2:53
SampsonSampson
264k74 gold badges538 silver badges561 bronze badges
2
I had to delete the quote marks, as well as the default for the changed field, as well as the default charset. Hopefully that won’t affect the data.
answered Jan 18, 2009 at 3:06
ElieElie
13.7k23 gold badges74 silver badges128 bronze badges
Here’s another way of writing it that might work for some: (left away most of the columns for brevity)
create table temp_books
(
id int not null,
start varchar(255) null,
constraint six_cb_datasource_pk
primary key (id)
);
answered Apr 18, 2020 at 10:43
MJLMJL
3523 silver badges11 bronze badges
0 / 0 / 0 Регистрация: 22.12.2020 Сообщений: 7 |
|
1 |
|
16.05.2021, 01:18. Показов 4052. Ответов 11
Здравствуйте! Помогите, пожалуйста. Нужна команда на SQL для создания четырех связанных таблиц в MS Access. Я пишу код, но при попытке сохранить его выскакивает сообщение «Ошибка синтаксиса в инструкции CREATE TABLE». Уже перерыла все методички, но решения проблемы так и не нашла. По методичке пишу правильно, но запрос упорно не хочет сохраняться. Должна получиться вот такая схема данных (см. вложение). Кликните здесь для просмотра всего текста
0 |
17230 / 7078 / 1586 Регистрация: 21.06.2012 Сообщений: 13,283 |
|
16.05.2021, 01:31 |
2 |
Возможно ли это реализовать? Возможно. Запросы нужно запускать по отдельности, так в Аксессе делается. А связи Вы и не создавали. Для их создания нужно делать CONSTRAINT … FOREIGN KEY.
1 |
0 / 0 / 0 Регистрация: 22.12.2020 Сообщений: 7 |
|
16.05.2021, 01:49 [ТС] |
3 |
Поняла, спасибо. Я пыталась писать запросы на создание таблиц со связями. Во вложении пример одного такого запроса. Таблица создается, а связь — нет. Что я делаю не так?.. Миниатюры
0 |
17230 / 7078 / 1586 Регистрация: 21.06.2012 Сообщений: 13,283 |
|
16.05.2021, 02:00 |
4 |
Выкладывайте SQL не картинками, а текстом, в тегах SQL. Нажали SQL (третья строка, 6 слева), появились и внутрь вставили текст. Ломать глаза, а потом стучать по клавишам нет никакого желания.
1 |
marusa122 0 / 0 / 0 Регистрация: 22.12.2020 Сообщений: 7 |
||||
16.05.2021, 02:06 [ТС] |
5 |
|||
Извините, я просто не знала, как это делать. Добавила.
0 |
ltv_1953 17230 / 7078 / 1586 Регистрация: 21.06.2012 Сообщений: 13,283 |
||||
16.05.2021, 02:18 |
6 |
|||
РешениеА CONSTRAINT где? И, естественно, таблицы Группы и Университеты должны быть созданы до выполнения этого запроса.
1 |
marusa122 0 / 0 / 0 Регистрация: 22.12.2020 Сообщений: 7 |
||||
16.05.2021, 02:44 [ТС] |
7 |
|||
Спасибо вам большое.
В режиме Конструктора (в уже созданной таблице) приходится вручную задавать маску ввода >L и правило проверки — «М» Or «Ж» . Возможно ли как-то дополнить запрос, чтобы при создании таблицы эти параметры устанавливались автоматически?
0 |
17230 / 7078 / 1586 Регистрация: 21.06.2012 Сообщений: 13,283 |
|
16.05.2021, 03:41 |
8 |
маску ввода > Это не маска ввода, а ограничение. Читайте документацию CONSTRAINT
1 |
0 / 0 / 0 Регистрация: 22.12.2020 Сообщений: 7 |
|
16.05.2021, 03:51 [ТС] |
9 |
Нет-нет, там именно маска ввода (она так и называется в Конструкторе)
0 |
17230 / 7078 / 1586 Регистрация: 21.06.2012 Сообщений: 13,283 |
|
16.05.2021, 04:09 |
10 |
Но куда вставлять и как оформлять в запросе маску ввода? Никуда. Нет такой возможности, если не конструкторе вручную, то только в VB, в DAO есть свойства полей таблицы. И все маски и т.п. (прочитал Вашу, как ограничение >1) лучше не делайте в таблицах, а только в формах. Вручную в таблицы вводить — дурной тон.
1 |
0 / 0 / 0 Регистрация: 22.12.2020 Сообщений: 7 |
|
16.05.2021, 04:18 [ТС] |
11 |
Большое вам спасибо))
0 |
17230 / 7078 / 1586 Регистрация: 21.06.2012 Сообщений: 13,283 |
|
16.05.2021, 04:42 |
12 |
Большое вам спасибо Да не за что. Все бы ТС так точно формулировали вопросы, воспринимали ответы, … .
1 |
Your MySQL query is incorrect. Correcting it to this works.
CREATE TABLE `comment_threads` (
`comment_id` INT(11) UNSIGNED NOT NULL DEFAULT '0',
`updated` TIMESTAMP NOT NULL ,
`timestamp` TIMESTAMP NOT NULL
) ENGINE=MyISAM;
To run this in phpMyAdmin, you can use the in-built table creator or enter the corrected SQL statement in the SQL query window.
Note that I removed the comma after the last TIMESTAMP NOT NULL
line (immediately before the ending )
.
UPDATE:
The second statement you posted corrects to this:
CREATE TABLE `comment_threads` (
`comment_id` INT(11) UNSIGNED NOT NULL DEFAULT '0',
`updated` TIMESTAMP NOT NULL ,
`timestamp` TIMESTAMP NOT NULL,
PRIMARY KEY(`comment_id`)
) ENGINE=MyISAM;
Here are the problems you introduced in your second CREATE TABLE
statement:
TIMESTAMP( 14 )
should just beTIMESTAMP
(per the documentation)- You need a comma after the line
TIMESTAMP NOT NULL
line. The comma is necessary now because unlike in the first example, you’re separated two parts of the statement: theTIMESTAMP NOT NULL
line and thePRIMARY KEY
declaration.
If you want more information on simple methods for debugging SQL statements, I strongly suggest you look at my answer to this question (see the section titled A bit more information on how to methodically fix errors like this).
Make sure that when you change a CREATE TABLE
statement, or any piece of code, that you make changes in small enough increments that you’re only «breaking at most one thing at a time.» In the case of your second CREATE TABLE
statement, there was no reason to change the first TIMESTAMP
declaration, and doing so broke the code. That line was working; no need to change it.
I received a MySQL data dump and am trying to insert the data into a set of temporary tables. The creation statement for the first table is shown below. When I run this I receive the 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 ''temp_books'( 'ID'int( 11 ) NOT NULL AUTO_INCREMENT, 'start'varchar( 20 ) ' at line 1
«. I’ve checked the documentation for MySQL syntax, and I don’t see that the problem is.
CREATE TABLE 'temp_books' (
'ID' int(11) NOT NULL AUTO_INCREMENT,
'start' varchar(20) NOT NULL,
'customer_id' int(11) NOT NULL DEFAULT '0',
'total_num' int(11) NOT NULL,
'amount' double(5,2) NOT NULL DEFAULT '0.00',
'changed' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ('ID'),
UNIQUE KEY 'start' ('start')
) ENGINE=MyISAM AUTO_INCREMENT=4853 DEFAULT CHARSET=latin1;
asked Jan 18, 2009 at 2:37
You shouldn’t put single-quotes on your identifiers. If you’re going to quote them use the «back tick» character (“`”). You can also use double-quotes but you have to specify that mode:
SET sql_mode='ANSI_QUOTES';
http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
answered Jan 18, 2009 at 3:09
TurnkeyTurnkey
9,1763 gold badges27 silver badges36 bronze badges
I’ve ALWAYS had issues with CREATE TABLE. Not sure why. Takes some trial-and-error.
Try this:
CREATE TABLE temp_books (
ID int(11) NOT NULL AUTO_INCREMENT,
start varchar(20) NOT NULL,
customer_id int(11) NOT NULL DEFAULT '0',
total_num int(11) NOT NULL,
amount double(5,2) NOT NULL DEFAULT '0.00',
changed timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (ID),
UNIQUE KEY start (start)
) ENGINE=MyISAM AUTO_INCREMENT=4853 DEFAULT CHARSET=latin1;
answered Jan 18, 2009 at 2:53
SampsonSampson
263k74 gold badges535 silver badges560 bronze badges
2
I had to delete the quote marks, as well as the default for the changed field, as well as the default charset. Hopefully that won’t affect the data.
answered Jan 18, 2009 at 3:06
ElieElie
13.5k23 gold badges74 silver badges128 bronze badges
Here’s another way of writing it that might work for some: (left away most of the columns for brevity)
create table temp_books
(
id int not null,
start varchar(255) null,
constraint six_cb_datasource_pk
primary key (id)
);
answered Apr 18, 2020 at 10:43
MJLMJL
3433 silver badges10 bronze badges
0 / 0 / 0 Регистрация: 22.12.2020 Сообщений: 7 |
|
1 |
|
16.05.2021, 01:18. Показов 3451. Ответов 11
Здравствуйте! Помогите, пожалуйста. Нужна команда на SQL для создания четырех связанных таблиц в MS Access. Я пишу код, но при попытке сохранить его выскакивает сообщение «Ошибка синтаксиса в инструкции CREATE TABLE». Уже перерыла все методички, но решения проблемы так и не нашла. По методичке пишу правильно, но запрос упорно не хочет сохраняться. Должна получиться вот такая схема данных (см. вложение). Кликните здесь для просмотра всего текста
__________________ 0 |
16778 / 6959 / 1548 Регистрация: 21.06.2012 Сообщений: 12,975 |
|
16.05.2021, 01:31 |
2 |
Возможно ли это реализовать? Возможно. Запросы нужно запускать по отдельности, так в Аксессе делается. А связи Вы и не создавали. Для их создания нужно делать CONSTRAINT … FOREIGN KEY. 1 |
0 / 0 / 0 Регистрация: 22.12.2020 Сообщений: 7 |
|
16.05.2021, 01:49 [ТС] |
3 |
Поняла, спасибо. Я пыталась писать запросы на создание таблиц со связями. Во вложении пример одного такого запроса. Таблица создается, а связь — нет. Что я делаю не так?.. Миниатюры
0 |
16778 / 6959 / 1548 Регистрация: 21.06.2012 Сообщений: 12,975 |
|
16.05.2021, 02:00 |
4 |
Выкладывайте SQL не картинками, а текстом, в тегах SQL. Нажали SQL (третья строка, 6 слева), появились и внутрь вставили текст. Ломать глаза, а потом стучать по клавишам нет никакого желания. 1 |
marusa122 0 / 0 / 0 Регистрация: 22.12.2020 Сообщений: 7 |
||||
16.05.2021, 02:06 [ТС] |
5 |
|||
Извините, я просто не знала, как это делать. Добавила.
0 |
ltv_1953 16778 / 6959 / 1548 Регистрация: 21.06.2012 Сообщений: 12,975 |
||||
16.05.2021, 02:18 |
6 |
|||
РешениеА CONSTRAINT где? И, естественно, таблицы Группы и Университеты должны быть созданы до выполнения этого запроса.
1 |
marusa122 0 / 0 / 0 Регистрация: 22.12.2020 Сообщений: 7 |
||||
16.05.2021, 02:44 [ТС] |
7 |
|||
Спасибо вам большое.
В режиме Конструктора (в уже созданной таблице) приходится вручную задавать маску ввода >L и правило проверки — «М» Or «Ж» . Возможно ли как-то дополнить запрос, чтобы при создании таблицы эти параметры устанавливались автоматически? 0 |
16778 / 6959 / 1548 Регистрация: 21.06.2012 Сообщений: 12,975 |
|
16.05.2021, 03:41 |
8 |
маску ввода > Это не маска ввода, а ограничение. Читайте документацию CONSTRAINT 1 |
0 / 0 / 0 Регистрация: 22.12.2020 Сообщений: 7 |
|
16.05.2021, 03:51 [ТС] |
9 |
Нет-нет, там именно маска ввода (она так и называется в Конструкторе) 0 |
16778 / 6959 / 1548 Регистрация: 21.06.2012 Сообщений: 12,975 |
|
16.05.2021, 04:09 |
10 |
Но куда вставлять и как оформлять в запросе маску ввода? Никуда. Нет такой возможности, если не конструкторе вручную, то только в VB, в DAO есть свойства полей таблицы. И все маски и т.п. (прочитал Вашу, как ограничение >1) лучше не делайте в таблицах, а только в формах. Вручную в таблицы вводить — дурной тон. 1 |
0 / 0 / 0 Регистрация: 22.12.2020 Сообщений: 7 |
|
16.05.2021, 04:18 [ТС] |
11 |
Большое вам спасибо)) 0 |
16778 / 6959 / 1548 Регистрация: 21.06.2012 Сообщений: 12,975 |
|
16.05.2021, 04:42 |
12 |
Большое вам спасибо Да не за что. Все бы ТС так точно формулировали вопросы, воспринимали ответы, … . 1 |
I keep getting the error message «Syntax error in CREATE TABLE statement» when I try to run the following CREATE VIEW statement in Access:
CREATE VIEW SeanWalshOrders (cNo, cName, street, city, county, discount)
AS
SELECT cNo, cName, street, city, county, discount
FROM orders
WHERE saleRepName = "Sean Walsh";
Gord Thompson
113k30 gold badges203 silver badges404 bronze badges
asked Nov 6, 2013 at 16:50
Tobias FunkeTobias Funke
1,3942 gold badges11 silver badges23 bronze badges
0
Your CREATE VIEW statement will work if executed using an OLEDB connection, e.g., from an external application or via the CurrentProject.Connection
object in Access VBA. However, Access does not accept CREATE VIEW statements when entered into the SQL pane of the Query Designer within Access itself (which uses a DAO connection, not OLEDB). In that context it is expecting a CREATE TABLE statement (as indicated by the error message.)
For more details see a related question here:
Attempting CREATE VIEW in Access gives «Syntax error in CREATE TABLE statement»
answered Nov 7, 2013 at 13:28
Gord ThompsonGord Thompson
113k30 gold badges203 silver badges404 bronze badges
I keep getting the error message «Syntax error in CREATE TABLE statement» when I try to run the following CREATE VIEW statement in Access:
CREATE VIEW SeanWalshOrders (cNo, cName, street, city, county, discount)
AS
SELECT cNo, cName, street, city, county, discount
FROM orders
WHERE saleRepName = "Sean Walsh";
Gord Thompson
113k30 gold badges203 silver badges404 bronze badges
asked Nov 6, 2013 at 16:50
Tobias FunkeTobias Funke
1,3942 gold badges11 silver badges23 bronze badges
0
Your CREATE VIEW statement will work if executed using an OLEDB connection, e.g., from an external application or via the CurrentProject.Connection
object in Access VBA. However, Access does not accept CREATE VIEW statements when entered into the SQL pane of the Query Designer within Access itself (which uses a DAO connection, not OLEDB). In that context it is expecting a CREATE TABLE statement (as indicated by the error message.)
For more details see a related question here:
Attempting CREATE VIEW in Access gives «Syntax error in CREATE TABLE statement»
answered Nov 7, 2013 at 13:28
Gord ThompsonGord Thompson
113k30 gold badges203 silver badges404 bronze badges
- Remove From My Forums
-
Question
-
My example Code as follows returns 3290 Syntax error in CREATE TABLE statement. I Have linked to my SQL Server 2008 Database using the ODBC String Below. I need to create tables from VBA. Please assist — Thanks and Regards Rhett.
Function CreateTableDDL()
On Error GoTo ErrorCom: InitGlobals
Dim strSql As String
‘Initialize
SntSQLConStr = «ODBC;Driver={SQL Server Native Client 10.0};Server=tcp:new.insuria.co.za,1433;Database=SNetData;Uid=Rhett;Pwd=Ibc270469;Encrypt=no;Connection Timeout=30;»
Set SDB = DBEngine.Workspaces(0).OpenDatabase(«», True, False, SntSQLConStr) ‘dbDriverNoPrompt
If Err.Number <> 0 Or SDB Is Nothing Then
MsgBox «Insuria Cannot Connect to the SQL SNetData Database.» & vbNewLine & «Contact Insuria for support…», vbOKOnly, «SQL SNetData Database Connection Failure»
Err.Clear: GoTo ErrorCom
End If
On Error GoTo ErrorCom: Err.Clear‘Create the Contractor table.
strSql = «CREATE TABLE dbo.ATest «
strSql = strSql & «(ConID INT CONSTRAINT ConID_PK PRIMARY KEY (ConID), «
strSql = strSql & «Surname NVARCHAR(MAX) NOT NULL, «
strSql = strSql & «FirstName NVARCHAR(MAX) NOT NULL);»
SDB.Execute strSql, dbFailOnError
ErrorCom: Debug.Print Err.Number, Err.Description: Stop: Err.Clear: Resume
If ErrCon(Err.Description, Err.Number, «ImportSNet: SNetTblChk») Then Resume
End Function
Rhett Cawood Insuria CRM Financial Planning Access Developer
- Edited by
Monday, November 11, 2013 7:30 AM
- Edited by
Answers
-
- Edited by
Van Dinh
Monday, November 11, 2013 1:33 PM
Typos - Marked as answer by
Fei XueMicrosoft employee
Sunday, November 17, 2013 1:31 PM
- Edited by
-
Build + Setup a pass though query in the query builder.
Then use this code:
strSql = your sql create command as you haveSet qdfPass = CurrentDb.QueryDefs(«MyPass»)
qdfPass.SQL = strSql
qdfPass.ExecuteSo once you have a pass-through query built then it rather easy to send commands to the server as per above, and even better is the above is min amount of code.
Albert D. Kallal (Access MVP)
Edmonton, Alberta Canada- Marked as answer by
Fei XueMicrosoft employee
Sunday, November 17, 2013 1:33 PM
- Marked as answer by
-
Rhett
You’re mixing apples and oranges. Thois example uses either user/pwd or trusted connection.
Dim cnn As ADODB.Connection Dim strSQL As String Dim cmd As ADODB.Command Set cnn = New ADODB.Connection ' 'OLEDB: ' 'Standard: ' strConnect = "Provider=sqloledb;Data Source=MySQLServer;Initial Catalog=MyDatabase;" _ ' & "User Id=sa;Password=asdasd;" 'Trusted: cnn.ConnectionString = "Provider=sqloledb;Data Source=MySQLServer;" _ & "Initial Catalog=MyDatabase;Integrated Security=SSPI;" cnn.ConnectionTimeout = 30 cnn.Open strSQL = "CREATE TABLE zzzzTest(ConID int IDENTITY(1,1) PRIMARY KEY, " _ & "LastName nvarchar(50), FirstName nvarchar(50))" Set cmd = New ADODB.Command cmd.ActiveConnection = cnn cmd.CommandType = adCmdText cmd.CommandText = strSQL Debug.Print cmd.CommandText cmd.Execute cnn.Close Set cmd = Nothing Set cnn = Nothing
Bill Mosca
www.thatlldoit.com
http://tech.groups.yahoo.com/group/MS_Access_Professionals- Marked as answer by
Fei XueMicrosoft employee
Sunday, November 17, 2013 1:33 PM
- Marked as answer by
CREATE TABLE plan
(
id VARCHAR(30) NOT NULL,
name VARCHAR(20),
amount INT,
interval INT,
currency CHAR(3),
object VARCHAR(20),
livemode BOOLEAN,
interval_count INT,
trial_period_days INT,
created TIMESTAMP,
updated TIMESTAMP,
deleted TIMESTAMP,
PRIMARY KEY (id)
);
Produces
'ERROR 1064 (42000): 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 'interval INT,
currency CHAR(3),
object ' at line 6'
Doesn’t work. However if the ‘l’ at the end of ‘interval’ is removed. It works.
CREATE TABLE plan
(
id VARCHAR(30) NOT NULL,
name VARCHAR(20),
amount INT,
interva INT,
currency CHAR(3),
object VARCHAR(20),
livemode BOOLEAN,
interval_count INT,
trial_period_days INT,
created TIMESTAMP,
updated TIMESTAMP,
deleted TIMESTAMP,
PRIMARY KEY (id)
);
I don’t understand if this is a problem with attempting to use ‘interval’ and ‘interval_count’. What’s going on here.