As a single query, the syntax you have posted works perfectly. You didn't include the END
to your BEGIN
block in the post, but we know that is not the issue because the error message would have had a different line number in it.
The following single expression will work:
(I like to indent the BEGIN but it makes no difference to the execution)
IF NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'control_forecastscenario'
AND TABLE_SCHEMA = 'rvfc')
BEGIN
CREATE TABLE [rvfc].[control_forecastscenario](
[Scenario] [varchar](255) NULL,
[Active] [varchar](255) NULL
)
END
Also note that I have omitted the ON [PRIMARY]
as that is the default file group and if you are not managing multiple file groups then it is better not to include references to them in your code base.
The only way to recreate your error is by trying to execute this as separate batched calls. This might happen if your business logic is executing a script in chunks or line by line, or if you have somehow built the query in a way that a batch terminator like GO
or ;
has been injected into the script.
The following will create your error.
IF NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'control_forecastscenario'
AND TABLE_SCHEMA = 'rvfc')
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ')'.
The same error will occur if a simi-colon in injected into the original script.
IF NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'control_forecastscenario'
AND TABLE_SCHEMA = 'rvfc')
;
BEGIN
CREATE TABLE [rvfc].[control_forecastscenario](
[Scenario] [varchar](255) NULL,
[Active] [varchar](255) NULL
)
END
In addressing some other comments, the existence of the schema rvfc
is not in question here, nor are other common syntax issues because they would raise different error messages like this:
Msg 2760, Level 16, State 1, Line 7
The specified schema name "rvfc" either does not exist or you do not have permission to use it.
If you have executed this statement, omitting the END
you would see a different line number, but the same message:
IF NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'control_forecastscenario'
AND TABLE_SCHEMA = 'rvfc') BEGIN
CREATE TABLE [rvfc].[control_forecastscenario](
[Scenario] [varchar](255) NULL,
[Active] [varchar](255) NULL
)
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near ')'.
The message is the same because the BEGIN
block requires closure with an END
which makes the entire BEGIN
block invalid. So )
was the last valid character in the script, so that is the last place SQL can report the error.
Please post your code that is executing the script for further assistance, otherwise this post should be closed as not reproducable.