Search code examples
c#sql-serversyntaxsmo

Unexpected Syntax Error "."


Background:

I am using SMO to read a script and then execute it on my database. There are parts of my script that need to change before I execute it, like the data of the databases.

The variable is cleansed and checked before it is allowed, and can only contain upper case letters.

The variable is this case is prefix.

However for some reason when I use a variable in this particular part of the script I get the below error.

enter image description here

Code:

The line of code that produces this error report is shown below.

sql += @"FROM dbo." + prefix + "reportEmails";

The full block of code can be seen below.

     sql += @"

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO";
            sql += Environment.NewLine;
            sql += @"CREATE VIEW [dbo].[" + prefix + "reportEmails]";
            sql += @"AS
SELECT     EmailID, EmailContent, EmailSubject, EmailTo, EmailFrom, UserID, ObjectValueID, EmailSent, EmailCreated, EmailRead, EmailFromName, EmailType, EmailFailed, 
                      CASE WHEN emailread IS NULL THEN 'Not Read' ELSE 'Read' END AS EmailStatus
FROM         DEReportingClient2DB.dbo.Emails AS Emails_1
WHERE     (UserID IN
                          (SELECT     UserID
                            FROM          DEReportingClient2DB.dbo.Users
                            WHERE      (ClientID = 195)))
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO";
            sql += Environment.NewLine;
            sql += @"CREATE VIEW [dbo].[" + prefix + "unreadEmails]";
            sql += @"AS
SELECT     COUNT(*) AS UnreadEmails, UserID";
            sql += @"FROM dbo." + prefix + "reportEmails";
sql += @"WHERE     (EmailRead IS NULL)
GROUP BY UserID
GO
...

Question:

Why am I getting this error?

Incorrect syntax near '.'


Solution

  • Answer

    After displaying what was actually being put into the variable SQL I discovered there were times where the code wasn't being put on a newline. This was causing joining of words.

    String in SQL Variable

    For Example, see line beginning with Select

    enter image description here

    Actual Solution

    Adding a newline before the keywords.

    sql+=Environment.NewLine;
    

    Example

                sql += Environment.NewLine;
                sql += @"CREATE VIEW [dbo].[" + prefix + "unreadEmails]";
                sql += Environment.NewLine;
                sql += @"AS";
                sql += Environment.NewLine;
                sql += @"SELECT     COUNT(*) AS UnreadEmails, UserID";
                sql += Environment.NewLine;
                sql += @"FROM dbo." + prefix + "reportEmails";
                sql += Environment.NewLine;