Ошибка incorrect syntax near the keyword from

При выполнении запроса

 select
      AllYears.Year,
      count(FirstVisitYears.Patient) as Count
    from 

        (select
          min(extract(YEAR from ReceptionDate)) as Year,
          Patient
        from Receptions
        where
          ReceptionType like 'Первич%'
        group by
          Patient
      ) as FirstVisitYears right join 
        (
          select distinct
            extract(YEAR from ReceptionDate) as Year
          from Receptions
        ) as AllYears on 
        FirstVisitYears.Year = AllYears.Year
    group by
      AllYears.Year

Возвращается ошибка
Помогите разобраться:)

Incorrect syntax near the keyword 'from'.

Пример работы SQLFiddle

  • sql
  • sql-server
  • запрос

задан 22 мая 2016 в 20:31

ka6an4eg's user avatar

ka6an4egka6an4eg

671 серебряный знак7 бронзовых знаков

1 ответ

Он ругается на конструкцию extract(YEAR from ReceptionDate).
Замените ее на YEAR(ReceptionDate) в обеих местах и все будет нормально.

Пример SqlFiddle

ответ дан 22 мая 2016 в 20:42

ApInvent's user avatar

ApInventApInvent

3,7971 золотой знак17 серебряных знаков27 бронзовых знаков

10

  • Тогда не правильно работает запрос уже. в MySQL все верно он выдавал. Вывод должен быть 1 2 0 (по столбцам)

    22 мая 2016 в 20:52

  • @ka6an4eg Поменял в примере фамилии написанные русским на транслит и все стало правильно. Я думаю, что sql fiddle просто схлопнул фамилии с одинаковым количеством символов т.к. он их не различил.

    22 мая 2016 в 20:59

  • @Aplnvent да, уже разобрался) При создании таблицы указал имена в Юникоде (N’Иванова’)

    22 мая 2016 в 21:04

  • @Aplnvent а скажи пожалуйста, если в создании таблицы указать «declare Orders table» , то из-за чего ошибка при выполнении запроса ?

    22 мая 2016 в 21:24

  • @ka6an4eg не совсем понял вопрос… При создании таблицы вообще нет ключевого слова declare. Что ты хотел получить этой конструкцией?

    22 мая 2016 в 21:34

User1107959781 posted

Hi, I have Error when I write this SQL statement retrieving the non selected facilitator for a specific course:

The SQL statement:<?xml:namespace prefix = o ns = «urn:schemas-microsoft-com:office:office» /><o:p></o:p>

<o:p> </o:p>

SELECT     facilitators.facilitator_id, facilitators.facilitator_name<o:p></o:p>

FROM        
facilitators INNER JOIN
<o:p></o:p>

                  
   [transaction_ facilitators] ON facilitators.facilitator_id <> [transaction_ facilitators].trans_Facilitator_id
<o:p></o:p>

WHERE     (NOT (facilitators.facilitator_id IN<o:p></o:p>

                         
(SELECT     [transaction_ facilitators].trans_Facilitator_id
<o:p></o:p>

    
                        FROM        
[transaction_ facilitators]
<o:p></o:p>

                            
WHERE     [transaction_ facilitators].trans_Course_id = 2)))
<o:p></o:p>

GROUP BY facilitators.facilitator_id, facilitators.facilitator_name<o:p></o:p>

ORDER BY facilitators.facilitator_id<o:p></o:p>

<o:p> </o:p>

Every thing goes right until I change this:<o:p></o:p>

WHERE     [transaction_ facilitators].trans_Course_id = 2<o:p></o:p>

To<o:p></o:p>

WHERE     [transaction_ facilitators].trans_Course_id = @course_id<o:p></o:p>

<o:p> </o:p>

It gives me this error:<o:p></o:p>

<o:p> </o:p>

Incorrect syntax near the keyword «From»<o:p></o:p>

<o:p> </o:p>

Any suggestion ??<o:p></o:p>

<o:p> </o:p>

  • Remove From My Forums
  • Question

  •  I have this code that I need to translate from oracle to Sql and I’m getting this error message «Msg 156, Level
    15, State 1, Line 26 Incorrect syntax near the keyword ‘FROM’.»

    The code is below.

    —Import Parcel
    DROP TABLE VISION_PARCEL
    SELECT * 
    INSERT INTO [dbo].[VISION_PARCEL]
    FROM [TOMSQLVISION].[VISION_2020].[REAL_PROP].[PARCEL]


    Chris

Answers

  • Try specifying columns in your select * into statements. If that would not work, you may need to use OPENQUERY instead.

    Also, you cannot just use DROP TABLE … without checking if it exists first. That’s why you can check with OBJECT_ID is not null syntax before DROP TABLE command.


    • Proposed as answer by

      Thursday, June 18, 2020 6:48 PM

    • Marked as answer by
      Padme Naberrie
      Monday, July 6, 2020 1:27 PM

  • DROP TABLE  IF EXISTS VISION_PARCEL;
    
    SELECT *
    
    
    INTO [dbo].[VISION_PARCEL] 
    
     
    FROM [TOMSQLVISION].[VISION_2020].[REAL_PROP].[PARCEL]
    
     

    • Proposed as answer by
      Naomi N
      Wednesday, June 17, 2020 5:27 PM
    • Marked as answer by
      Padme Naberrie
      Monday, July 6, 2020 1:26 PM

  • drop table if exists vision_parcel;

    select *

    into dbo.Vision_Parcel

    from [TOMSQLVISION].[VISION_2020].[REAL_PROP].[PARCEL]

    This will create a new Vision_Parcel table in the current database.

    Also, are you trying to use linked server? If not, you don’t have to use server name in front of the database name.


    • Marked as answer by
      Padme Naberrie
      Monday, July 6, 2020 1:27 PM

  • I added the new code now I’m getting this error message

    Msg 156, Level 15, State 1, Line 23
    Incorrect syntax near the keyword ‘IF’.

    DROP TABLE  IF EXISTS VISION_PARCEL;
    SELECT *
    INTO [dbo].[VISION_PARCEL] 
    FROM [TOMSQLVISION].[VISION_2020].[REAL_PROP].[PARCEL]


    Chris

    • Marked as answer by
      Padme Naberrie
      Monday, July 6, 2020 1:27 PM

  • You need to check whether you have a database there or not.  Drop if syntax is for newere SQL Server

    DROP TABLE   VISION_PARCEL;
    SELECT *
    INTO [dbo].[VISION_PARCEL] 
    FROM [TOMSQLVISION].[VISION_2020].[REAL_PROP].[PARCEL]

    • Marked as answer by
      Padme Naberrie
      Monday, July 6, 2020 1:27 PM

  • Can you post result of your SQL Server version, e.g.

    select @@VERSION

    I don’t remember which version this syntax was added to, but if you can use alternative more verbose syntax, e.g.

    if object_id(‘dbo.Vision_Parcel’, N’U’) is not null drop table dbo.Vision_Parcel;


    • Edited by
      Naomi N
      Wednesday, June 17, 2020 6:04 PM
    • Marked as answer by
      Padme Naberrie
      Monday, July 6, 2020 1:27 PM

  • I’m still getting the error message «Msg 156, Level 15, State 1, Line 23
    Incorrect syntax near the keyword ‘IF’.»  I’ve tried everyone’s suggestions.  I am accessing the data from another connected  sql server.  It is also a query that I converted from Oracle to sql.  The servers operating system is
    Windows Server 2012 R2 and SQL Server 2012.  Any suggestions.


    Chris

    • Marked as answer by
      Padme Naberrie
      Monday, July 6, 2020 1:27 PM

  • Are you trying to drop table from other linked SQL Server ?

    Then you need to give complete name as LinkedServerName.DatabaseName.SchemaName.TableName

    IF OBJECT_ID('yourdbdbname..VISION_PARCEL') IS NOT NULL DROP TABLE VISION_PARCEL
    GO

    Thanks
    Atul

    • Marked as answer by
      Padme Naberrie
      Monday, July 6, 2020 1:27 PM

  • Hi Chris,

    IF  EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.Vision_Parcel') 
        AND type = N'U')
    DROP TABLE dbo.Vision_Parcel
    GO
    SELECT * 
    INTO [dbo].[VISION_PARCEL]
    FROM [TOMSQLVISION].[VISION_2020].[REAL_PROP].[PARCEL]

    Best Regards,

    Lily


    MSDN Community Support
    Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to
    MSDN Support, feel free to contact MSDNFSF@microsoft.com

    • Marked as answer by
      Padme Naberrie
      Monday, July 6, 2020 1:27 PM

  • hi

    Are you using link server for connecting to oracle . If so follow the bellow link and use open query ,DBLNK_TEST is the link server name

    Link a SQL Server to an Oracle database

    SELECT * FROM OPENQUERY([DBLNK_TEST] , ‘select * from FROM [TOMSQLVISION].[VISION_2020].[REAL_PROP].[PARCEL]’) ; 

    • Proposed as answer by
      Naomi N
      Thursday, June 18, 2020 2:02 PM
    • Marked as answer by
      Padme Naberrie
      Monday, July 6, 2020 1:27 PM

  • Hi Lily and everyone else,

    The above code worked but now I’m getting these error messages.  I’m linking SQL server to SQL server but this code was originally to get data from an oracle db then move it to a SQL database then to a web page.

    These are the error messages.

    OLE DB provider «SQLNCLI11» for linked server «TOMSQLVISION» returned message «Deferred prepare could not be completed.».
    Msg 8180, Level 16, State 1, Line 1
    Statement(s) could not be prepared.
    Msg 207, Level 16, State 1, Line 26
    Invalid column name ‘SLH_OWN_PCT’.
    Msg 207, Level 16, State 1, Line 24
    Invalid column name ‘SLH_OWN_ID’.
    Msg 207, Level 16, State 1, Line 22
    Invalid column name ‘SLH_OWN_ADDR2’.
    Msg 207, Level 16, State 1, Line 14
    Invalid column name ‘SLH_BOOK_PG’.
    Msg 207, Level 16, State 1, Line 13
    Invalid column name ‘SLH_COUNTRY’.
    Msg 207, Level 16, State 1, Line 12
    Invalid column name ‘SLH_ZIP’.
    Msg 207, Level 16, State 1, Line 11
    Invalid column name ‘SLH_STT’.
    Msg 207, Level 16, State 1, Line 10
    Invalid column name ‘SLH_CITY’.
    Msg 207, Level 16, State 1, Line 9
    Invalid column name ‘SLH_OWN_ADDR’.
    Msg 207, Level 16, State 1, Line 8
    Invalid column name ‘SLH_CO_OWN_NAME’.
    Msg 207, Level 16, State 1, Line 7
    Invalid column name ‘SLH_OWN_NAME’.

    This is the code below

    — Begin importing data
    — Import Realmast
    USE TAXPAYER

    DROP TABLE VISION_REALMAST
    SELECT * 
    INTO dbo.VISION_REALMAST
    FROM [TOMSQLVISION].[VISION_2020].[REAL_PROP].[REALMAST]
    —DROP THE PUBLIC EMPLOYEES
    DELETE FROM dbo.VISION_REALMAST 
    WHERE REM_INET_SUPPRESS = 1 
    — Update the GIS ID field in realmast
    UPDATE dbo.VISION_REALMAST
    SET REM_GIS_ID = CAST(CAST(REM_MBLU_MAP AS INT) AS VARCHAR(20))  +’-‘+ CAST(CAST(REM_MBLU_BLOCK AS INT) AS VARCHAR(20))

    — Import Land
    DROP TABLE VISION_LAND
    SELECT * 
    INTO VISION_LAND
    FROM [TOMSQLVISION].[VISION_2020].[REAL_PROP].[LAND]

    —Import Parcel
    IF  EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N’dbo.Vision_Parcel’) 
        AND type = N’U’)
    DROP TABLE dbo.Vision_Parcel
    GO
    SELECT * 
    INTO [dbo].[VISION_PARCEL]
    FROM [TOMSQLVISION].[VISION_2020].[REAL_PROP].[PARCEL]

    Thanks for all of the help.

    Chris


    Chris

    • Marked as answer by
      Padme Naberrie
      Monday, July 6, 2020 1:27 PM

  • The «IF EXISTS» was added to SQL 2016+.  You cannot use that syntax in SQL 2012.

    • Marked as answer by
      Padme Naberrie
      Monday, July 6, 2020 1:26 PM

  • Hi Chris,

    The issue is related to a new thread: Statement(s)
    could not be prepared. It’s so kind of you to mark helpful replies as answers in order to close this thread, and continue the topic in the new thread.

    Best Regards,

    Lily


    MSDN Community Support
    Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to
    MSDN Support, feel free to contact MSDNFSF@microsoft.com

    • Marked as answer by
      Padme Naberrie
      Monday, July 6, 2020 1:26 PM

When I execute the following code:

USE Database
GO

DECLARE @DF Datetime = CONVERT(datetime,'30/01/2017',103)
DECLARE @DT Datetime = CONVERT(datetime,'13/03/2017',103)

DECLARE @Owner nvarchar(255) = 'user@email.co.uk'
DECLARE @Box nvarchar(255) = 'Sent Items'
DECLARE @ResultTo int = 0
DECLARE @ResultCC int = 0
DECLARE @ResultBCC int = 0

SET @ResultTo = COUNT(ToEmailAddress) FROM EmailTo 
WHERE fkDataExtractTableID IN 
    (
        SELECT DataExtractTableID
        FROM [Database].[dbo].[DataExtractTable]
        WHERE (DateSent between @DF AND @DT)
        AND ([Owner] = @Owner)
        AND (Box = @Box)
      )

I get this error message:

Msg 156, Level 15, State 1, Line 12
Incorrect syntax near the keyword ‘FROM’.

What am I missing?

marc_s's user avatar

marc_s

721k173 gold badges1320 silver badges1442 bronze badges

asked Oct 16, 2017 at 0:05

Siv's user avatar

2

I think your sql wrong on line 12. It may be like this:

SET @ResultTo = (select COUNT(ToEmailAddress) FROM EmailTo)

answered Oct 16, 2017 at 0:37

I Love You's user avatar

I Love YouI Love You

2582 silver badges8 bronze badges

1

Change your variable assignment to:

select @ResultTo = count(ToEmailAddress) from EmailTo

Felix Pamittan's user avatar

answered Oct 16, 2017 at 0:51

thomas's user avatar

thomasthomas

2,5921 gold badge28 silver badges44 bronze badges

1

You can’t use 2 different syntax in a select query. Either use Set statement or use simple query

Set Statement — where you set a single variable as a return from a select query

SET @ResultTo = (Select COUNT(ToEmailAddress) FROM EmailTo 
WHERE fkDataExtractTableID IN 
    (
        SELECT DataExtractTableID
        FROM [Database].[dbo].[DataExtractTable]
        WHERE (DateSent between @DF AND @DT)
        AND ([Owner] = @Owner)
        AND (Box = @Box)
      ) )

Or Select statement where you set multiple variables value like

Select @ResultTo = COUNT(ToEmailAddress)  
--Aslo define other variable, if you want
-- like @ResultTo1 , but this query is aggregation, so only aggeregate function use
FROM EmailTo 
WHERE fkDataExtractTableID IN 
    (
        SELECT DataExtractTableID
        FROM [Database].[dbo].[DataExtractTable]
        WHERE (DateSent between @DF AND @DT)
        AND ([Owner] = @Owner)
        AND (Box = @Box)
      )

answered Oct 16, 2017 at 4:54

Ajay2707's user avatar

Ajay2707Ajay2707

5,6686 gold badges39 silver badges58 bronze badges

Below is the corrected one:

DECLARE @DF Datetime = CONVERT(datetime,'30/01/2017',103)
DECLARE @DT Datetime = CONVERT(datetime,'13/03/2017',103)

    DECLARE @Owner nvarchar(255) = 'user@email.co.uk'
    DECLARE @Box nvarchar(255) = 'Sent Items'
    Declare @ResultTo int = 0
    Declare @ResultCC int = 0
    Declare @ResultBCC int = 0

    SELECT @ResultTo = COUNT(ToEmailAddress) FROM EmailTo 
    WHERE fkDataExtractTableID IN 
    (
        SELECT DataExtractTableID
        FROM [Database].[dbo].[DataExtractTable]
        WHERE (DateSent between @DF AND @DT)
        AND ([Owner] = @Owner)
        AND (Box = @Box)
      )

answered Oct 16, 2017 at 2:35

Khorshed Alam's user avatar

2

User1107959781 posted

Hi, I have Error when I write this SQL statement retrieving the non selected facilitator for a specific course:

The SQL statement:<?xml:namespace prefix = o ns = «urn:schemas-microsoft-com:office:office» /><o:p></o:p>

<o:p> </o:p>

SELECT     facilitators.facilitator_id, facilitators.facilitator_name<o:p></o:p>

FROM        
facilitators INNER JOIN
<o:p></o:p>

                  
   [transaction_ facilitators] ON facilitators.facilitator_id <> [transaction_ facilitators].trans_Facilitator_id
<o:p></o:p>

WHERE     (NOT (facilitators.facilitator_id IN<o:p></o:p>

                         
(SELECT     [transaction_ facilitators].trans_Facilitator_id
<o:p></o:p>

    
                        FROM        
[transaction_ facilitators]
<o:p></o:p>

                            
WHERE     [transaction_ facilitators].trans_Course_id = 2)))
<o:p></o:p>

GROUP BY facilitators.facilitator_id, facilitators.facilitator_name<o:p></o:p>

ORDER BY facilitators.facilitator_id<o:p></o:p>

<o:p> </o:p>

Every thing goes right until I change this:<o:p></o:p>

WHERE     [transaction_ facilitators].trans_Course_id = 2<o:p></o:p>

To<o:p></o:p>

WHERE     [transaction_ facilitators].trans_Course_id = @course_id<o:p></o:p>

<o:p> </o:p>

It gives me this error:<o:p></o:p>

<o:p> </o:p>

Incorrect syntax near the keyword «From»<o:p></o:p>

<o:p> </o:p>

Any suggestion ??<o:p></o:p>

<o:p> </o:p>

I have a code that is supposed to create an XML output file. I have everything working except getting an error on the from:

SELECT 
  (SELECT ‘ADD’ as ‘@action-code’,’CLINICAL’ as ‘@data’, ‘OUTPATIENT’ AS ‘@type’, ‘1.0’ as ‘@version’,
   (SELECT CONVERT(VARCHAR(10),CAST(GETDATE() AS DATE), 110) AS ‘create-date’,
    CONVERT(VARCHAR(5),GETDATE(),108) AS ‘create-time’, ‘xxxxx’ AS ‘create-by’,
    ‘SQL2008’ as ‘version’, ‘SQL’ as ‘create-by-tool’
    FOR XML PATH(‘file-audit-data’),type,ELEMENTS),
   (SELECT [provider-id],[npi] 
    ,(SELECT [first-name], [last-name], birthdate, sex, race, ethnic,[postal-code] 
,(SELECT ‘ED-THROUGHPUT’ AS ‘@measure-set’ 
,[encounter-date]
,[arrival-time]
,a.[patient-id]
,(SELECT DISCHGCODE AS ‘@answer-code’, ‘DISCHGCODE’ as ‘@question-cd’, ‘0’ as ‘@row-number’
FROM POP2 detail
     WHERE detail.[patient-id] = POP2.[patient-id]
FOR XML PATH(‘detail’),type)

,(SELECT EDDEPARTDT AS ‘@answer-code’, ‘EDDEPARTDT’ as ‘@question-cd’, ‘0’ as ‘@row-number’
FROM POP2 detail
     WHERE detail.[patient-id] = POP2.[patient-id]
FOR XML PATH(‘detail’),type)  
,(SELECT EDDEPARTTM AS ‘@answer-code’, ‘EDDEPARTTM’ as ‘@question-cd’, ‘0’ as ‘@row-number’
FROM POP2 detail
     WHERE detail.[patient-id] = POP2.[patient-id]
FOR XML PATH(‘detail’),type)  
,(SELECT emcode AS ‘@answer-code’, ‘EMCODE’ as ‘@question-cd’, ‘0’ as ‘@row-number’
FROM POP2 detail
WHERE detail.[patient-id] = POP2.[patient-id]
FOR XML PATH(‘detail’),type)
,(SELECT PRINDX  AS ‘@answer-code’, ‘PRINDX ‘ as ‘@question-cd’, ‘0’ as ‘@row-number’
  
FROM POP2 detail
WHERE detail.[patient-id] = POP2.[patient-id]
FOR XML PATH(‘detail’),type)
,(SELECT pmtsrce AS ‘@answer-code’, ‘PMTSRCE’ as ‘@question-cd’, ‘0’ as ‘@row-number’
FROM POP2 detail
WHERE detail.[patient-id] = POP2.[patient-id]
FOR XML PATH(‘detail’),type)
 
—> FROM POP2 x <— this is where the error stops
    WHERE x.[patient-id] = [mhtest].[dbo].[pop2].[patient-id]
    FOR XML PATH(‘encounter’), type, ELEMENTS)
  FROM [mhtest].[dbo].[vw_RPT_ADHOC_DATA_DUMP]z
  WHERE z.[n_PATIENT_ID] = [mhtest].[dbo].[pop2].[patient-id]
  FOR XML PATH(‘patient’), type, ELEMENTS)
 FROM [mhtest].[dbo].[pop2] z
 WHERE z.[patient-id] = [mhtest].[dbo].[pop2].[patient-id]
 FOR XML PATH(‘provider’), type, ELEMENTS)—End Provider —
FROM [mhtest].[dbo].[pop2] y
WHERE y.[patient-id] = [mhtest].[dbo].[pop2].[patient-id]
ORDER BY NEWID()
FOR XML PATH(‘submission’), type, ELEMENTS)OP18
INTO TOP18z — temp xml table—

Any thoughts as to why this would be?

  • Remove From My Forums
  • Question

  • Hi all,
    i am trying to run this sql but its giving me the error .
    Incorrect syntax near the keyword ‘from’.

    the query is suppose to return 1 or 0 depending on the condition.

    Regards

    • Edited by
      sva0008
      Thursday, March 4, 2010 7:22 PM

Answers

  • You are missing the END for the CASE expression. Also, avoid using reserved keywords for object names, like «User».

    CASE WHEN u.[User] IS NULL THEN 0 ELSE 1 END

    Plamen Ratchev

    • Marked as answer by
      sva0008
      Thursday, March 4, 2010 7:21 PM
  • Remove From My Forums
  • Question

  • Hi all,
    i am trying to run this sql but its giving me the error .
    Incorrect syntax near the keyword ‘from’.

    the query is suppose to return 1 or 0 depending on the condition.

    Regards

    • Edited by
      sva0008
      Thursday, March 4, 2010 7:22 PM

Answers

  • You are missing the END for the CASE expression. Also, avoid using reserved keywords for object names, like «User».

    CASE WHEN u.[User] IS NULL THEN 0 ELSE 1 END

    Plamen Ratchev

    • Marked as answer by
      sva0008
      Thursday, March 4, 2010 7:21 PM

Я пишу SQL-запрос, но продолжаю получать синтаксическую ошибку:

Incorrect syntax near the keyword ‘GROUP’

Что могло вызвать эту проблему? Я попытался найти все очевидные вещи, но не заметил этого, и я также просмотрел предыдущие сообщения, см. Запрос ниже:

(/****** Script for SelectTopNRows command from SSMS  ******/
SELECT ALLGENEDX.[id]
      ,ALLGENEDX.[Chr]
      ,ALLGENEDX.[Start]
      ,ALLGENEDX.[End]
      ,ALLGENEDX.[ref]
      ,ALLGENEDX.[alt]
      ,ALLGENEDX.[Func#refGene]
      ,ALLGENEDX.[Gene#refGene]
      ,ALLGENEDX.[Otherinfo]
      ,CASE WHEN OTHERINFO = 'HOM' THEN CASE WHEN PARENT_OTHERINFO = 'HET' THEN 1 ELSE 0 END ELSE CASE WHEN PARENT_OTHERINFO <> 'HOM' AND PARENT_AMMOUNT > 1 THEN 1 ELSE 0 END END AS 'PARENT_INFO'
      ,CASE WHEN OTHERINFO = 'HOM' THEN CASE WHEN SIBLING_OTHERINFO = 'HET' THEN 1 ELSE 0 END ELSE CASE WHEN SIBLING_OTHERINFO <> 'HOM' AND (SIBLING_AMMOUNT = 1 OR SIBLING_AMMOUNT IS NULL) THEN 1 ELSE 2 END END AS 'SIBLING_INFO' 
      FROM [Exome Data].[dbo].[ALLGENEDX],
(SELECT [ID],
[Chr],
[Start],
[end],
[REF], 
[ALT],
[Func#refGene],
[GENE#REFGENE],
[OTHERINFO] AS PARENT_OTHERINFO, 
COUNT (ID) OVER (PARTITION BY 
[Chr],
[Start],
[End],
[REF], 
[ALT],
[Func#refGene],
[GENE#REFGENE],
[OTHERINFO]) AS PARENT_AMMOUNT 
FROM [Exome Data].DBO.ALLGENEDX 
WHERE ID IN ('1646304GD', '1646307GD'))AS PARENT, 
(SELECT [id],
[Chr],
[Start],
[end],
[REF], 
[ALT],
[Func#refGene],
[GENE#REFGENE],
[OTHERINFO] AS SIBLING_OTHERINFO, 
COUNT (ID) OVER (PARTITION BY
[Chr],
[Start],
[end],
[REF], 
[ALT],
[Func#refGene],
[GENE#REFGENE],
[OTHERINFO]) AS SIBLING_AMMOUNT 
FROM [Exome Data].DBO.ALLGENEDX 
WHERE ID IN ('1646310GD', '1646314GD', '1646317GD', '1646320GD', '1646325GD'))AS SIBLING
   WHERE SIBLING.[CHR]=ALLGENEDX.Chr
  AND SIBLING.[START]=ALLGENEDX.[START]
  AND SIBLING.[END]=ALLGENEDX.[END]
  AND SIBLING.[REF]=ALLGENEDX.[REF]
  AND SIBLING.[ALT]= ALLGENEDX.[ALT] 
  AND SIBLING.[GENE#REFGENE]=ALLGENEDX.[GENE#REFGENE]
  AND PARENT.[CHR]=ALLGENEDX.[Chr]
  AND PARENT.[START]=ALLGENEDX.[START]
  AND PARENT.[END]=ALLGENEDX.[END]
  AND PARENT.[REF]=ALLGENEDX.[REF]
  AND PARENT.[ALT]= ALLGENEDX.[ALT] 
  AND PARENT.[GENE#REFGENE]=ALLGENEDX.[GENE#REFGENE]
  AND  ALLGENEDX.ID= '1646299GD' AND ALLGENEDX.Func#refGene = 'exonic' 
  AND (EXAC_FREQ<'0.005' OR EXAC_FREQ IS NULL)
  AND ([1000G_ALL]<'0.005' OR [1000G_ALL] IS NULL)
  AND (GNOMAD_EXOME_ALL<'0.005' OR GNOMAD_EXOME_ALL IS NULL)
  HAVING CASE WHEN OTHERINFO = 'HOM' THEN CASE WHEN PARENT_OTHERINFO = 'HET' THEN 1 ELSE 0 END ELSE CASE WHEN PARENT_OTHERINFO <> 'HOM' AND PARENT_AMMOUNT > 1 THEN 1 ELSE 0 END END > 0
  OR CASE WHEN OTHERINFO = 'HOM' THEN CASE WHEN SIBLING_OTHERINFO = 'HET' THEN 1 ELSE 0 END ELSE CASE WHEN SIBLING_OTHERINFO <> 'HOM' AND (SIBLING_AMMOUNT = 1 OR SIBLING_AMMOUNT IS NULL) THEN 1 ELSE 2 END END > 0
  GROUP BY ALLGENEDX.[id]
      ,ALLGENEDX.[Chr]
      ,ALLGENEDX.[Start]
      ,ALLGENEDX.[End]
      ,ALLGENEDX.[ref]
      ,ALLGENEDX.[alt]
      ,ALLGENEDX.[Func#refGene]
      ,ALLGENEDX.[Gene#refGene]
      ,ALLGENEDX.[Otherinfo]
      ,[PARENT_OTHERINFO]
      ,[SIBLING_OTHERINFO]
     ORDER BY len ALLGENEDX.[Chr], Chr, start;/****** Script for SelectTopNRows command from SSMS  ******/
SELECT ALLGENEDX.[id]
      ,ALLGENEDX.[Chr]
      ,ALLGENEDX.[Start]
      ,ALLGENEDX.[End]
      ,ALLGENEDX.[ref]
      ,ALLGENEDX.[alt]
      ,ALLGENEDX.[Func#refGene]
      ,ALLGENEDX.[Gene#refGene]
      ,ALLGENEDX.[Otherinfo]
      ,CASE WHEN OTHERINFO = 'HOM' THEN CASE WHEN PARENT_OTHERINFO = 'HET' THEN 1 ELSE 0 END ELSE CASE WHEN PARENT_OTHERINFO <> 'HOM' AND PARENT_AMMOUNT > 1 THEN 1 ELSE 0 END END AS 'PARENT_INFO'
      ,CASE WHEN OTHERINFO = 'HOM' THEN CASE WHEN SIBLING_OTHERINFO = 'HET' THEN 1 ELSE 0 END ELSE CASE WHEN SIBLING_OTHERINFO <> 'HOM' AND (SIBLING_AMMOUNT = 1 OR SIBLING_AMMOUNT IS NULL) THEN 1 ELSE 2 END END AS 'SIBLING_INFO' 
      FROM [Exome Data].[dbo].[ALLGENEDX],
(SELECT [ID],
[Chr],
[Start],
[end],
[REF], 
[ALT],
[Func#refGene],
[GENE#REFGENE],
[OTHERINFO] AS PARENT_OTHERINFO, 
COUNT (ID) OVER (PARTITION BY 
[Chr],
[Start],
[End],
[REF], 
[ALT],
[Func#refGene],
[GENE#REFGENE],
[OTHERINFO]) AS PARENT_AMMOUNT 
FROM [Exome Data].DBO.ALLGENEDX 
WHERE ID IN ('1646304GD', '1646307GD'))AS PARENT, 
(SELECT [id],
[Chr],
[Start],
[end],
[REF], 
[ALT],
[Func#refGene],
[GENE#REFGENE],
[OTHERINFO] AS SIBLING_OTHERINFO, 
COUNT (ID) OVER (PARTITION BY
[Chr],
[Start],
[end],
[REF], 
[ALT],
[Func#refGene],
[GENE#REFGENE],
[OTHERINFO]) AS SIBLING_AMMOUNT 
FROM [Exome Data].DBO.ALLGENEDX 
WHERE ID IN ('1646310GD', '1646314GD', '1646317GD', '1646320GD', '1646325GD'))AS SIBLING
   WHERE SIBLING.[CHR]=ALLGENEDX.Chr
  AND SIBLING.[START]=ALLGENEDX.[START]
  AND SIBLING.[END]=ALLGENEDX.[END]
  AND SIBLING.[REF]=ALLGENEDX.[REF]
  AND SIBLING.[ALT]= ALLGENEDX.[ALT] 
  AND SIBLING.[GENE#REFGENE]=ALLGENEDX.[GENE#REFGENE]
  AND PARENT.[CHR]=ALLGENEDX.[Chr]
  AND PARENT.[START]=ALLGENEDX.[START]
  AND PARENT.[END]=ALLGENEDX.[END]
  AND PARENT.[REF]=ALLGENEDX.[REF]
  AND PARENT.[ALT]= ALLGENEDX.[ALT] 
  AND PARENT.[GENE#REFGENE]=ALLGENEDX.[GENE#REFGENE]
  AND  ALLGENEDX.ID= '1646299GD' AND ALLGENEDX.Func#refGene = 'exonic' 
  AND (EXAC_FREQ<'0.005' OR EXAC_FREQ IS NULL)
  AND ([1000G_ALL]<'0.005' OR [1000G_ALL] IS NULL)
  AND (GNOMAD_EXOME_ALL<'0.005' OR GNOMAD_EXOME_ALL IS NULL)
  HAVING CASE WHEN OTHERINFO = 'HOM' THEN CASE WHEN PARENT_OTHERINFO = 'HET' THEN 1 ELSE 0 END ELSE CASE WHEN PARENT_OTHERINFO <> 'HOM' AND PARENT_AMMOUNT > 1 THEN 1 ELSE 0 END END > 0
  OR CASE WHEN OTHERINFO = 'HOM' THEN CASE WHEN SIBLING_OTHERINFO = 'HET' THEN 1 ELSE 0 END ELSE CASE WHEN SIBLING_OTHERINFO <> 'HOM' AND (SIBLING_AMMOUNT = 1 OR SIBLING_AMMOUNT IS NULL) THEN 1 ELSE 2 END END > 0
  GROUP BY ALLGENEDX.[id]
      ,ALLGENEDX.[Chr]
      ,ALLGENEDX.[Start]
      ,ALLGENEDX.[End]
      ,ALLGENEDX.[ref]
      ,ALLGENEDX.[alt]
      ,ALLGENEDX.[Func#refGene]
      ,ALLGENEDX.[Gene#refGene]
      ,ALLGENEDX.[Otherinfo]
      ,[PARENT_OTHERINFO]
      ,[SIBLING_OTHERINFO]
     ORDER BY len ALLGENEDX.[Chr], Chr, start;

Rod9i

3 / 3 / 1

Регистрация: 12.05.2016

Сообщений: 17

1

15.05.2017, 12:10. Показов 8333. Ответов 1

Метки нет (Все метки)


здравствуйте!
задача сделать бд с добавлением, обновлением, удалением, поиском и
команды написаны, но с кучей ошибок
одна из них: System.Data.SqlClient.SqlException: «Incorrect syntax near the keyword ‘Table’.»
подскажите как решить эту проблему?

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private void button1_Click(object sender, EventArgs e)//добавить
 
        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "insert into Table values ('" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + dateTimePicker1.Text + "','" + dateTimePicker2.Text+ "') ";
            cmd.ExecuteNonQuery();
            con.Close();
            textBox3.Text = "";
            textBox4.Text = "";
            textBox5.Text = "";
            
            disp_data();
            MessageBox.Show("Запись добавлена!");
        }
        public void disp_data()
        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Select* from Table";   //ошибка здесь
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

Даценд

Эксперт .NET

5856 / 4733 / 2940

Регистрация: 20.04.2015

Сообщений: 8,361

15.05.2017, 13:09

2

Лучший ответ Сообщение было отмечено Rod9i как решение

Решение

Rod9i,
TABLE — зарезервированное слово языка SQL.
При использовании в запросе в качестве имени таблицы или поля это слово нужно заключать в квадратные скобки.

C#
22
cmd.CommandText = "Select* from [Table]";

Кстати, в строке 7 такая же ситуация.

3

Hi All,

I’m trying to get data from an SQL 2005 server using synchronous JDBC receiver adapter. I’m using PI 7.0. My outgoing message is as follows:

<?xml version=»1.0″ encoding=»UTF-8″ ?>

— http://holding.com/brd/»>

— <STATEMENT>

— <ECZ_IZIN_YUKU action=»SELECT»>

<table>ECZ_IZIN_YUKU</table>

<access />

— <key>

<iy_yil compareOperation=»GT»>1900</iy_yil>

</key>

</ECZ_IZIN_YUKU>

</STATEMENT>

</ns0:MT_IZIN_YUKU_REQ>

I’ve found the following log in the trace file:

#1.5#0014C23BCFC900630000003D000013B000042740B0A858B1#1169058702046#/Applications/ExchangeInfrastructure/AdapterFramework/Services/ADAPTER/ADMIN/JDBC#sap.com/com.sap.aii.af.app#com.sap.aii.adapter.jdbc.XI2JDBC.onInternalMessageBinary(Message)#J2EE_GUEST#0####fa10f5f0a65811db84410014c23bcfc9#XI XI2JDBC[CC_JDBC_RECI_BRD_TO_BHT/HUMANIST/]_2574##0#0#Error#1#com.sap.aii.adapter.jdbc.XI2JDBC#Plain###Error processing request, rollback: Error processing request in sax parser: Error when executing statement for table/stored proc. ‘ECZ_IZIN_YUKU’ (structure ‘STATEMENT’): com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword ‘FROM’.#

Thanks a lot..

User1107959781 posted

Hi, I have Error when I write this SQL statement retrieving the non selected facilitator for a specific course:

The SQL statement:<?xml:namespace prefix = o ns = «urn:schemas-microsoft-com:office:office» /><o:p></o:p>

<o:p> </o:p>

SELECT     facilitators.facilitator_id, facilitators.facilitator_name<o:p></o:p>

FROM        
facilitators INNER JOIN
<o:p></o:p>

                  
   [transaction_ facilitators] ON facilitators.facilitator_id <> [transaction_ facilitators].trans_Facilitator_id
<o:p></o:p>

WHERE     (NOT (facilitators.facilitator_id IN<o:p></o:p>

                         
(SELECT     [transaction_ facilitators].trans_Facilitator_id
<o:p></o:p>

    
                        FROM        
[transaction_ facilitators]
<o:p></o:p>

                            
WHERE     [transaction_ facilitators].trans_Course_id = 2)))
<o:p></o:p>

GROUP BY facilitators.facilitator_id, facilitators.facilitator_name<o:p></o:p>

ORDER BY facilitators.facilitator_id<o:p></o:p>

<o:p> </o:p>

Every thing goes right until I change this:<o:p></o:p>

WHERE     [transaction_ facilitators].trans_Course_id = 2<o:p></o:p>

To<o:p></o:p>

WHERE     [transaction_ facilitators].trans_Course_id = @course_id<o:p></o:p>

<o:p> </o:p>

It gives me this error:<o:p></o:p>

<o:p> </o:p>

Incorrect syntax near the keyword «From»<o:p></o:p>

<o:p> </o:p>

Any suggestion ??<o:p></o:p>

<o:p> </o:p>

When I execute the following code:

USE Database
GO

DECLARE @DF Datetime = CONVERT(datetime,'30/01/2017',103)
DECLARE @DT Datetime = CONVERT(datetime,'13/03/2017',103)

DECLARE @Owner nvarchar(255) = 'user@email.co.uk'
DECLARE @Box nvarchar(255) = 'Sent Items'
DECLARE @ResultTo int = 0
DECLARE @ResultCC int = 0
DECLARE @ResultBCC int = 0

SET @ResultTo = COUNT(ToEmailAddress) FROM EmailTo 
WHERE fkDataExtractTableID IN 
    (
        SELECT DataExtractTableID
        FROM [Database].[dbo].[DataExtractTable]
        WHERE (DateSent between @DF AND @DT)
        AND ([Owner] = @Owner)
        AND (Box = @Box)
      )

I get this error message:

Msg 156, Level 15, State 1, Line 12
Incorrect syntax near the keyword ‘FROM’.

What am I missing?

marc_s's user avatar

marc_s

721k173 gold badges1320 silver badges1442 bronze badges

asked Oct 16, 2017 at 0:05

Siv's user avatar

2

I think your sql wrong on line 12. It may be like this:

SET @ResultTo = (select COUNT(ToEmailAddress) FROM EmailTo)

answered Oct 16, 2017 at 0:37

I Love You's user avatar

I Love YouI Love You

2582 silver badges8 bronze badges

1

Change your variable assignment to:

select @ResultTo = count(ToEmailAddress) from EmailTo

Felix Pamittan's user avatar

answered Oct 16, 2017 at 0:51

thomas's user avatar

thomasthomas

2,5921 gold badge28 silver badges44 bronze badges

1

You can’t use 2 different syntax in a select query. Either use Set statement or use simple query

Set Statement — where you set a single variable as a return from a select query

SET @ResultTo = (Select COUNT(ToEmailAddress) FROM EmailTo 
WHERE fkDataExtractTableID IN 
    (
        SELECT DataExtractTableID
        FROM [Database].[dbo].[DataExtractTable]
        WHERE (DateSent between @DF AND @DT)
        AND ([Owner] = @Owner)
        AND (Box = @Box)
      ) )

Or Select statement where you set multiple variables value like

Select @ResultTo = COUNT(ToEmailAddress)  
--Aslo define other variable, if you want
-- like @ResultTo1 , but this query is aggregation, so only aggeregate function use
FROM EmailTo 
WHERE fkDataExtractTableID IN 
    (
        SELECT DataExtractTableID
        FROM [Database].[dbo].[DataExtractTable]
        WHERE (DateSent between @DF AND @DT)
        AND ([Owner] = @Owner)
        AND (Box = @Box)
      )

answered Oct 16, 2017 at 4:54

Ajay2707's user avatar

Ajay2707Ajay2707

5,6686 gold badges39 silver badges58 bronze badges

Below is the corrected one:

DECLARE @DF Datetime = CONVERT(datetime,'30/01/2017',103)
DECLARE @DT Datetime = CONVERT(datetime,'13/03/2017',103)

    DECLARE @Owner nvarchar(255) = 'user@email.co.uk'
    DECLARE @Box nvarchar(255) = 'Sent Items'
    Declare @ResultTo int = 0
    Declare @ResultCC int = 0
    Declare @ResultBCC int = 0

    SELECT @ResultTo = COUNT(ToEmailAddress) FROM EmailTo 
    WHERE fkDataExtractTableID IN 
    (
        SELECT DataExtractTableID
        FROM [Database].[dbo].[DataExtractTable]
        WHERE (DateSent between @DF AND @DT)
        AND ([Owner] = @Owner)
        AND (Box = @Box)
      )

answered Oct 16, 2017 at 2:35

Khorshed Alam's user avatar

2

User1107959781 posted

Hi, I have Error when I write this SQL statement retrieving the non selected facilitator for a specific course:

The SQL statement:<?xml:namespace prefix = o ns = «urn:schemas-microsoft-com:office:office» /><o:p></o:p>

<o:p> </o:p>

SELECT     facilitators.facilitator_id, facilitators.facilitator_name<o:p></o:p>

FROM        
facilitators INNER JOIN
<o:p></o:p>

                  
   [transaction_ facilitators] ON facilitators.facilitator_id <> [transaction_ facilitators].trans_Facilitator_id
<o:p></o:p>

WHERE     (NOT (facilitators.facilitator_id IN<o:p></o:p>

                         
(SELECT     [transaction_ facilitators].trans_Facilitator_id
<o:p></o:p>

    
                        FROM        
[transaction_ facilitators]
<o:p></o:p>

                            
WHERE     [transaction_ facilitators].trans_Course_id = 2)))
<o:p></o:p>

GROUP BY facilitators.facilitator_id, facilitators.facilitator_name<o:p></o:p>

ORDER BY facilitators.facilitator_id<o:p></o:p>

<o:p> </o:p>

Every thing goes right until I change this:<o:p></o:p>

WHERE     [transaction_ facilitators].trans_Course_id = 2<o:p></o:p>

To<o:p></o:p>

WHERE     [transaction_ facilitators].trans_Course_id = @course_id<o:p></o:p>

<o:p> </o:p>

It gives me this error:<o:p></o:p>

<o:p> </o:p>

Incorrect syntax near the keyword «From»<o:p></o:p>

<o:p> </o:p>

Any suggestion ??<o:p></o:p>

<o:p> </o:p>

I have a code that is supposed to create an XML output file. I have everything working except getting an error on the from:

SELECT 
  (SELECT ‘ADD’ as ‘@action-code’,’CLINICAL’ as ‘@data’, ‘OUTPATIENT’ AS ‘@type’, ‘1.0’ as ‘@version’,
   (SELECT CONVERT(VARCHAR(10),CAST(GETDATE() AS DATE), 110) AS ‘create-date’,
    CONVERT(VARCHAR(5),GETDATE(),108) AS ‘create-time’, ‘xxxxx’ AS ‘create-by’,
    ‘SQL2008’ as ‘version’, ‘SQL’ as ‘create-by-tool’
    FOR XML PATH(‘file-audit-data’),type,ELEMENTS),
   (SELECT [provider-id],[npi] 
    ,(SELECT [first-name], [last-name], birthdate, sex, race, ethnic,[postal-code] 
,(SELECT ‘ED-THROUGHPUT’ AS ‘@measure-set’ 
,[encounter-date]
,[arrival-time]
,a.[patient-id]
,(SELECT DISCHGCODE AS ‘@answer-code’, ‘DISCHGCODE’ as ‘@question-cd’, ‘0’ as ‘@row-number’
FROM POP2 detail
     WHERE detail.[patient-id] = POP2.[patient-id]
FOR XML PATH(‘detail’),type)

,(SELECT EDDEPARTDT AS ‘@answer-code’, ‘EDDEPARTDT’ as ‘@question-cd’, ‘0’ as ‘@row-number’
FROM POP2 detail
     WHERE detail.[patient-id] = POP2.[patient-id]
FOR XML PATH(‘detail’),type)  
,(SELECT EDDEPARTTM AS ‘@answer-code’, ‘EDDEPARTTM’ as ‘@question-cd’, ‘0’ as ‘@row-number’
FROM POP2 detail
     WHERE detail.[patient-id] = POP2.[patient-id]
FOR XML PATH(‘detail’),type)  
,(SELECT emcode AS ‘@answer-code’, ‘EMCODE’ as ‘@question-cd’, ‘0’ as ‘@row-number’
FROM POP2 detail
WHERE detail.[patient-id] = POP2.[patient-id]
FOR XML PATH(‘detail’),type)
,(SELECT PRINDX  AS ‘@answer-code’, ‘PRINDX ‘ as ‘@question-cd’, ‘0’ as ‘@row-number’
  
FROM POP2 detail
WHERE detail.[patient-id] = POP2.[patient-id]
FOR XML PATH(‘detail’),type)
,(SELECT pmtsrce AS ‘@answer-code’, ‘PMTSRCE’ as ‘@question-cd’, ‘0’ as ‘@row-number’
FROM POP2 detail
WHERE detail.[patient-id] = POP2.[patient-id]
FOR XML PATH(‘detail’),type)
 
—> FROM POP2 x <— this is where the error stops
    WHERE x.[patient-id] = [mhtest].[dbo].[pop2].[patient-id]
    FOR XML PATH(‘encounter’), type, ELEMENTS)
  FROM [mhtest].[dbo].[vw_RPT_ADHOC_DATA_DUMP]z
  WHERE z.[n_PATIENT_ID] = [mhtest].[dbo].[pop2].[patient-id]
  FOR XML PATH(‘patient’), type, ELEMENTS)
 FROM [mhtest].[dbo].[pop2] z
 WHERE z.[patient-id] = [mhtest].[dbo].[pop2].[patient-id]
 FOR XML PATH(‘provider’), type, ELEMENTS)—End Provider —
FROM [mhtest].[dbo].[pop2] y
WHERE y.[patient-id] = [mhtest].[dbo].[pop2].[patient-id]
ORDER BY NEWID()
FOR XML PATH(‘submission’), type, ELEMENTS)OP18
INTO TOP18z — temp xml table—

Any thoughts as to why this would be?

  • Remove From My Forums
  • Question

  • Hi all,
    i am trying to run this sql but its giving me the error .
    Incorrect syntax near the keyword ‘from’.

    the query is suppose to return 1 or 0 depending on the condition.

    Regards

    • Edited by
      sva0008
      Thursday, March 4, 2010 7:22 PM

Answers

  • You are missing the END for the CASE expression. Also, avoid using reserved keywords for object names, like «User».

    CASE WHEN u.[User] IS NULL THEN 0 ELSE 1 END

    Plamen Ratchev

    • Marked as answer by
      sva0008
      Thursday, March 4, 2010 7:21 PM
  • Remove From My Forums
  • Question

  • Hi all,
    i am trying to run this sql but its giving me the error .
    Incorrect syntax near the keyword ‘from’.

    the query is suppose to return 1 or 0 depending on the condition.

    Regards

    • Edited by
      sva0008
      Thursday, March 4, 2010 7:22 PM

Answers

  • You are missing the END for the CASE expression. Also, avoid using reserved keywords for object names, like «User».

    CASE WHEN u.[User] IS NULL THEN 0 ELSE 1 END

    Plamen Ratchev

    • Marked as answer by
      sva0008
      Thursday, March 4, 2010 7:21 PM

Я пишу SQL-запрос, но продолжаю получать синтаксическую ошибку:

Incorrect syntax near the keyword ‘GROUP’

Что могло вызвать эту проблему? Я попытался найти все очевидные вещи, но не заметил этого, и я также просмотрел предыдущие сообщения, см. Запрос ниже:

(/****** Script for SelectTopNRows command from SSMS  ******/
SELECT ALLGENEDX.[id]
      ,ALLGENEDX.[Chr]
      ,ALLGENEDX.[Start]
      ,ALLGENEDX.[End]
      ,ALLGENEDX.[ref]
      ,ALLGENEDX.[alt]
      ,ALLGENEDX.[Func#refGene]
      ,ALLGENEDX.[Gene#refGene]
      ,ALLGENEDX.[Otherinfo]
      ,CASE WHEN OTHERINFO = 'HOM' THEN CASE WHEN PARENT_OTHERINFO = 'HET' THEN 1 ELSE 0 END ELSE CASE WHEN PARENT_OTHERINFO <> 'HOM' AND PARENT_AMMOUNT > 1 THEN 1 ELSE 0 END END AS 'PARENT_INFO'
      ,CASE WHEN OTHERINFO = 'HOM' THEN CASE WHEN SIBLING_OTHERINFO = 'HET' THEN 1 ELSE 0 END ELSE CASE WHEN SIBLING_OTHERINFO <> 'HOM' AND (SIBLING_AMMOUNT = 1 OR SIBLING_AMMOUNT IS NULL) THEN 1 ELSE 2 END END AS 'SIBLING_INFO' 
      FROM [Exome Data].[dbo].[ALLGENEDX],
(SELECT [ID],
[Chr],
[Start],
[end],
[REF], 
[ALT],
[Func#refGene],
[GENE#REFGENE],
[OTHERINFO] AS PARENT_OTHERINFO, 
COUNT (ID) OVER (PARTITION BY 
[Chr],
[Start],
[End],
[REF], 
[ALT],
[Func#refGene],
[GENE#REFGENE],
[OTHERINFO]) AS PARENT_AMMOUNT 
FROM [Exome Data].DBO.ALLGENEDX 
WHERE ID IN ('1646304GD', '1646307GD'))AS PARENT, 
(SELECT [id],
[Chr],
[Start],
[end],
[REF], 
[ALT],
[Func#refGene],
[GENE#REFGENE],
[OTHERINFO] AS SIBLING_OTHERINFO, 
COUNT (ID) OVER (PARTITION BY
[Chr],
[Start],
[end],
[REF], 
[ALT],
[Func#refGene],
[GENE#REFGENE],
[OTHERINFO]) AS SIBLING_AMMOUNT 
FROM [Exome Data].DBO.ALLGENEDX 
WHERE ID IN ('1646310GD', '1646314GD', '1646317GD', '1646320GD', '1646325GD'))AS SIBLING
   WHERE SIBLING.[CHR]=ALLGENEDX.Chr
  AND SIBLING.[START]=ALLGENEDX.[START]
  AND SIBLING.[END]=ALLGENEDX.[END]
  AND SIBLING.[REF]=ALLGENEDX.[REF]
  AND SIBLING.[ALT]= ALLGENEDX.[ALT] 
  AND SIBLING.[GENE#REFGENE]=ALLGENEDX.[GENE#REFGENE]
  AND PARENT.[CHR]=ALLGENEDX.[Chr]
  AND PARENT.[START]=ALLGENEDX.[START]
  AND PARENT.[END]=ALLGENEDX.[END]
  AND PARENT.[REF]=ALLGENEDX.[REF]
  AND PARENT.[ALT]= ALLGENEDX.[ALT] 
  AND PARENT.[GENE#REFGENE]=ALLGENEDX.[GENE#REFGENE]
  AND  ALLGENEDX.ID= '1646299GD' AND ALLGENEDX.Func#refGene = 'exonic' 
  AND (EXAC_FREQ<'0.005' OR EXAC_FREQ IS NULL)
  AND ([1000G_ALL]<'0.005' OR [1000G_ALL] IS NULL)
  AND (GNOMAD_EXOME_ALL<'0.005' OR GNOMAD_EXOME_ALL IS NULL)
  HAVING CASE WHEN OTHERINFO = 'HOM' THEN CASE WHEN PARENT_OTHERINFO = 'HET' THEN 1 ELSE 0 END ELSE CASE WHEN PARENT_OTHERINFO <> 'HOM' AND PARENT_AMMOUNT > 1 THEN 1 ELSE 0 END END > 0
  OR CASE WHEN OTHERINFO = 'HOM' THEN CASE WHEN SIBLING_OTHERINFO = 'HET' THEN 1 ELSE 0 END ELSE CASE WHEN SIBLING_OTHERINFO <> 'HOM' AND (SIBLING_AMMOUNT = 1 OR SIBLING_AMMOUNT IS NULL) THEN 1 ELSE 2 END END > 0
  GROUP BY ALLGENEDX.[id]
      ,ALLGENEDX.[Chr]
      ,ALLGENEDX.[Start]
      ,ALLGENEDX.[End]
      ,ALLGENEDX.[ref]
      ,ALLGENEDX.[alt]
      ,ALLGENEDX.[Func#refGene]
      ,ALLGENEDX.[Gene#refGene]
      ,ALLGENEDX.[Otherinfo]
      ,[PARENT_OTHERINFO]
      ,[SIBLING_OTHERINFO]
     ORDER BY len ALLGENEDX.[Chr], Chr, start;/****** Script for SelectTopNRows command from SSMS  ******/
SELECT ALLGENEDX.[id]
      ,ALLGENEDX.[Chr]
      ,ALLGENEDX.[Start]
      ,ALLGENEDX.[End]
      ,ALLGENEDX.[ref]
      ,ALLGENEDX.[alt]
      ,ALLGENEDX.[Func#refGene]
      ,ALLGENEDX.[Gene#refGene]
      ,ALLGENEDX.[Otherinfo]
      ,CASE WHEN OTHERINFO = 'HOM' THEN CASE WHEN PARENT_OTHERINFO = 'HET' THEN 1 ELSE 0 END ELSE CASE WHEN PARENT_OTHERINFO <> 'HOM' AND PARENT_AMMOUNT > 1 THEN 1 ELSE 0 END END AS 'PARENT_INFO'
      ,CASE WHEN OTHERINFO = 'HOM' THEN CASE WHEN SIBLING_OTHERINFO = 'HET' THEN 1 ELSE 0 END ELSE CASE WHEN SIBLING_OTHERINFO <> 'HOM' AND (SIBLING_AMMOUNT = 1 OR SIBLING_AMMOUNT IS NULL) THEN 1 ELSE 2 END END AS 'SIBLING_INFO' 
      FROM [Exome Data].[dbo].[ALLGENEDX],
(SELECT [ID],
[Chr],
[Start],
[end],
[REF], 
[ALT],
[Func#refGene],
[GENE#REFGENE],
[OTHERINFO] AS PARENT_OTHERINFO, 
COUNT (ID) OVER (PARTITION BY 
[Chr],
[Start],
[End],
[REF], 
[ALT],
[Func#refGene],
[GENE#REFGENE],
[OTHERINFO]) AS PARENT_AMMOUNT 
FROM [Exome Data].DBO.ALLGENEDX 
WHERE ID IN ('1646304GD', '1646307GD'))AS PARENT, 
(SELECT [id],
[Chr],
[Start],
[end],
[REF], 
[ALT],
[Func#refGene],
[GENE#REFGENE],
[OTHERINFO] AS SIBLING_OTHERINFO, 
COUNT (ID) OVER (PARTITION BY
[Chr],
[Start],
[end],
[REF], 
[ALT],
[Func#refGene],
[GENE#REFGENE],
[OTHERINFO]) AS SIBLING_AMMOUNT 
FROM [Exome Data].DBO.ALLGENEDX 
WHERE ID IN ('1646310GD', '1646314GD', '1646317GD', '1646320GD', '1646325GD'))AS SIBLING
   WHERE SIBLING.[CHR]=ALLGENEDX.Chr
  AND SIBLING.[START]=ALLGENEDX.[START]
  AND SIBLING.[END]=ALLGENEDX.[END]
  AND SIBLING.[REF]=ALLGENEDX.[REF]
  AND SIBLING.[ALT]= ALLGENEDX.[ALT] 
  AND SIBLING.[GENE#REFGENE]=ALLGENEDX.[GENE#REFGENE]
  AND PARENT.[CHR]=ALLGENEDX.[Chr]
  AND PARENT.[START]=ALLGENEDX.[START]
  AND PARENT.[END]=ALLGENEDX.[END]
  AND PARENT.[REF]=ALLGENEDX.[REF]
  AND PARENT.[ALT]= ALLGENEDX.[ALT] 
  AND PARENT.[GENE#REFGENE]=ALLGENEDX.[GENE#REFGENE]
  AND  ALLGENEDX.ID= '1646299GD' AND ALLGENEDX.Func#refGene = 'exonic' 
  AND (EXAC_FREQ<'0.005' OR EXAC_FREQ IS NULL)
  AND ([1000G_ALL]<'0.005' OR [1000G_ALL] IS NULL)
  AND (GNOMAD_EXOME_ALL<'0.005' OR GNOMAD_EXOME_ALL IS NULL)
  HAVING CASE WHEN OTHERINFO = 'HOM' THEN CASE WHEN PARENT_OTHERINFO = 'HET' THEN 1 ELSE 0 END ELSE CASE WHEN PARENT_OTHERINFO <> 'HOM' AND PARENT_AMMOUNT > 1 THEN 1 ELSE 0 END END > 0
  OR CASE WHEN OTHERINFO = 'HOM' THEN CASE WHEN SIBLING_OTHERINFO = 'HET' THEN 1 ELSE 0 END ELSE CASE WHEN SIBLING_OTHERINFO <> 'HOM' AND (SIBLING_AMMOUNT = 1 OR SIBLING_AMMOUNT IS NULL) THEN 1 ELSE 2 END END > 0
  GROUP BY ALLGENEDX.[id]
      ,ALLGENEDX.[Chr]
      ,ALLGENEDX.[Start]
      ,ALLGENEDX.[End]
      ,ALLGENEDX.[ref]
      ,ALLGENEDX.[alt]
      ,ALLGENEDX.[Func#refGene]
      ,ALLGENEDX.[Gene#refGene]
      ,ALLGENEDX.[Otherinfo]
      ,[PARENT_OTHERINFO]
      ,[SIBLING_OTHERINFO]
     ORDER BY len ALLGENEDX.[Chr], Chr, start;

Rod9i

3 / 3 / 1

Регистрация: 12.05.2016

Сообщений: 17

1

15.05.2017, 12:10. Показов 8333. Ответов 1

Метки нет (Все метки)


здравствуйте!
задача сделать бд с добавлением, обновлением, удалением, поиском и
команды написаны, но с кучей ошибок
одна из них: System.Data.SqlClient.SqlException: «Incorrect syntax near the keyword ‘Table’.»
подскажите как решить эту проблему?

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private void button1_Click(object sender, EventArgs e)//добавить
 
        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "insert into Table values ('" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + dateTimePicker1.Text + "','" + dateTimePicker2.Text+ "') ";
            cmd.ExecuteNonQuery();
            con.Close();
            textBox3.Text = "";
            textBox4.Text = "";
            textBox5.Text = "";
            
            disp_data();
            MessageBox.Show("Запись добавлена!");
        }
        public void disp_data()
        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Select* from Table";   //ошибка здесь
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

Даценд

Эксперт .NET

5856 / 4733 / 2940

Регистрация: 20.04.2015

Сообщений: 8,361

15.05.2017, 13:09

2

Лучший ответ Сообщение было отмечено Rod9i как решение

Решение

Rod9i,
TABLE — зарезервированное слово языка SQL.
При использовании в запросе в качестве имени таблицы или поля это слово нужно заключать в квадратные скобки.

C#
22
cmd.CommandText = "Select* from [Table]";

Кстати, в строке 7 такая же ситуация.

3

Hi All,

I’m trying to get data from an SQL 2005 server using synchronous JDBC receiver adapter. I’m using PI 7.0. My outgoing message is as follows:

<?xml version=»1.0″ encoding=»UTF-8″ ?>

— http://holding.com/brd/»>

— <STATEMENT>

— <ECZ_IZIN_YUKU action=»SELECT»>

<table>ECZ_IZIN_YUKU</table>

<access />

— <key>

<iy_yil compareOperation=»GT»>1900</iy_yil>

</key>

</ECZ_IZIN_YUKU>

</STATEMENT>

</ns0:MT_IZIN_YUKU_REQ>

I’ve found the following log in the trace file:

#1.5#0014C23BCFC900630000003D000013B000042740B0A858B1#1169058702046#/Applications/ExchangeInfrastructure/AdapterFramework/Services/ADAPTER/ADMIN/JDBC#sap.com/com.sap.aii.af.app#com.sap.aii.adapter.jdbc.XI2JDBC.onInternalMessageBinary(Message)#J2EE_GUEST#0####fa10f5f0a65811db84410014c23bcfc9#XI XI2JDBC[CC_JDBC_RECI_BRD_TO_BHT/HUMANIST/]_2574##0#0#Error#1#com.sap.aii.adapter.jdbc.XI2JDBC#Plain###Error processing request, rollback: Error processing request in sax parser: Error when executing statement for table/stored proc. ‘ECZ_IZIN_YUKU’ (structure ‘STATEMENT’): com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword ‘FROM’.#

Thanks a lot..

Incorrect syntax near is an error message in SQL Server because you’re using the wrong syntax for a SQL query or the query contains unprintable characters that are invincible to the naked eye.Copy of Incorrect Syntax Near in SQL Server

This article will show you SQL statements that will lead to the “incorrect syntax near” error, and we’ll show you solutions that you can use to solve similar errors in your environment.

Before you proceed, know that we’re aware of how frustrating this error can get, and that’s why this article will analyze the “incorrect syntax near ‘ ‘ meaning” as a way to make it easy for you.

With that out of the way, launch your SQL Server, and let’s teach you “how to fix incorrect syntax near ‘ ‘ in SQL Server.

Contents

  • Why Do Your SQL Statements Have an Incorrect Syntax?
    • – Typographical Error in Your SQL Statement
    • – Misusing a Keyword or Reserved Words
    • – SQL Statements Have Misplaced Punctuation Marks
    • – An Unprintable Characters in Your SQL Statement
  • How To Fix the Syntax Errors in Your SQL Statements?
    • – Check for Typographical Error in Your SQL Statement
    • – Avoid Using Reserved Words as Your Column Names
    • – Use Punctuation Marks the Right Way
    • – Use a Text Editor To Show the Unprintable Characters
  • Conclusion

Why Do Your SQL Statements Have an Incorrect Syntax?

Your SQL statements have an incorrect syntax because of the following:

  • You have a typographical error in your SQL statement
  • You’re misusing a keyword or reserved words
  • Your SQL statements have misplaced punctuation marks
  • You have unprintable characters in your SQL statement

– Typographical Error in Your SQL Statement

Typographical errors are a common cause of the “incorrect syntax near ‘-‘. SQL date” error in SQL Server. These errors occur when there is a mistake in the way that the SQL statement is written, such as a misspelled keyword or a missing punctuation mark.

For example, given the following SQL code that will create a “Customers” table:

CREATE TABLE Customers (

CustomerID INT PRIMARY KEY,

FirstName VARCHAR(50),

LastName VARCHAR(50),

Email VARCHAR(100),

Phone VARCHAR(20),

Address VARCHAR(200),

City VARCHAR(50),

State VARCHAR(50),

ZipCode VARCHAR(10)

);

INSERT INTO Customers (CustomerID, FirstName, LastName, Email, Phone, Address, City, State, ZipCode)

VALUES

(1, ‘John’, ‘Doe’, ‘johndoe@site.com’, ‘123-456-7890’, ‘123 Main St’, ‘New York’, ‘NY’, ‘10001’),

(2, ‘Jane’, ‘Doe’, ‘janedoe@site.com’, ‘123-456-7890’, ‘456 Elm St’, ‘Los Angeles’, ‘CA’, ‘90001’),

(3, ‘Bob’, ‘Smith’, ‘bobsmith@site.com’, ‘123-456-7890’, ‘789 Oak St’, ‘Chicago’, ‘IL’, ‘60601’),

(4, ‘Alice’, ‘Johnson’, ‘alicejohnson@site.com’, ‘123-456-7890’, ‘321 Pine St’, ‘Houston’, ‘TX’, ‘77001’);

The following SQL will result in a syntax error because there is a typographical error in the keyword “FORM” which should be “FROM”:

– Misusing a Keyword or Reserved Words

SQL Server has a list of reserved words that you cannot use as identifiers for tables, columns, or other objects. So, any attempt to use a reserved word as an identifier, can lead to the “incorrect syntax near ‘ ‘ in visual studio“.Copy of Fix the Syntax Errors in SQL Statements

For example, the following SQL statement will result in an error because “SELECT” and “TABLE” are reserved words that you cannot use as column names.

CREATE TABLE BIKE_TWO (

SELECT VARCHAR(15),

TABLE INT);

The following is another example, but this time, we typed the “FROM” keyword twice, and this will also cause an error.

SELECT FROM FROM Customers;

– SQL Statements Have Misplaced Punctuation Marks

A misplaced punctuation mark can cause the “incorrect syntax near ‘;’.” error in SQL Server, and this can happen when you’re trying to retrieve a record from a table.

For example, the following will result in a syntax error because the name that we’re retrieving contains quotes that cause the error. That’s because SQL will not understand how to parse the “SELECT” statement.

SELECT * FROM Customers WHERE Customers.FirstName = ‘O’Brien’

The same error will also occur in the following code and that’s because there we used a quote in the wrong way.

UPDATE Customers SET Lastname = ‘Doe’, ‘FirstName’ = ‘Jane’ WHERE CustomerID = 2;

– An Unprintable Characters in Your SQL Statement

In SQL Server, unprintable characters can cause the “incorrect syntax near ‘ ‘. in SQL Server 2019” error because they are mostly hidden, and they can alter the structure of an SQL statement. As a result, SQL Server cannot read and parse the statement correctly, so it returns a syntax error.

For example, in the following SQL, there is a Unicode character after the “e” in “Doe”, and it will cause the “incorrect syntax near” error. To confirm, copy the code, and run it against the “Customers” table that you created earlier.

SELECT * FROM Customers

WHERE LastName = ‘Doe’•

How To Fix the Syntax Errors in Your SQL Statements?

To fix the syntax errors in your SQL statements, you can:

  • Check for a typographical error in your SQL statement
  • Avoid using reserved words as your column names
  • Use punctuation marks the right way
  • Use a text editor to show the unprintable characters

– Check for Typographical Error in Your SQL Statement

Your first routine when you see the “incorrect syntax near” error is to check your SQL statements for typographical errors.

For example, the following code is a previous example that resulted in the error:

The next SQL is the correct version of the statement, and the fix is to change “FORM” to “FROM”. This will make it a valid SQL that the SQL server will parse without throwing a syntax error.

– Avoid Using Reserved Words as Your Column Names

Another way to prevent the incorrect syntax error in SQL Server is to avoid using reserved words as your column names. It’s recommended to use descriptive names that will make maintenance easy for you and other developers in the future.

However, if you need a reserved word as a column name, there is a way to do that.

For reference, the following is a previous example that’s trying to create the BIKE_TWO table in SQL Server:

CREATE TABLE BIKE_TWO (

SELECT VARCHAR(15),

TABLE INT);

The SQL code contains two reserved names; “SELECT” and “TABLE” that SQL Server will not allow. To fix this, you can place square brackets around them, and the code will run fine:

CREATE TABLE BIKE_TWO(

[SELECT] VARCHAR(15),

[TABLE] INT);

– Use Punctuation Marks the Right Way

Using punctuation the right way in SQL Server will prevent the “incorrect syntax near ‘.’. SQL Server stored procedure“. That’s because the server will understand your SQL queries and return a result (if applicable). For a start, have a look at the following SQL that we showed you earlier:

SELECT * FROM Customers WHERE Customers.FirstName = ‘O’Brien’

The customer’s first name has quotes that we used directly in the query, and this led to an error.Fixing of Incorrect Syntax Near

The fix is to use another punctuation mark before the “B” in Brien, and this will tell SQL Server that “O” and “Brien” are two separate words in quotes. This will allow it to parse the statement without throwing a syntax error.

SELECT * FROM Customers WHERE Customers.Name = ‘O”Brien’

Another example is the following SQL statement that we also showed you earlier, but we did not mention what caused the error. Observe the code for a second time, and you will see that we used quotes around a table name. This is wrong and that’s why the SQL Server shows a syntax error.

–This is wrong. 

UPDATE Customers SET Lastname = ‘Doe’, ‘FirstName’ = ‘Janee’ WHERE CustomerID = 2;

The solution is to remove the quotes from the “FirstName” column, and this cements the concept of using punctuation marks the right way.

— This is correct

UPDATE Customers SET Lastname = ‘Gonzalez’, FirstName = ‘Jonathan’ WHERE CustomerID = 2;

– Use a Text Editor To Show the Unprintable Characters

Using a text editor is the ultimate tool to solve the “incorrect syntax near ‘ ‘. in C#” error when your code has no syntax error and yet, SQL Server says otherwise.

If you’re in such a situation, do the following:

  1. Download Notepad++ from their official website and install it on your computer.
  2. Open Notepad++, and click on “New file”
  3. Ensure the value of the “Encoding” menu is “Encode in UTF-8”. If it’s not there, set it.
  4. Copy your SQL statements that are failing in SQL Server, and paste them in Notepad++.
  5. Click the “Encoding” menu again, and change it to “Encode in ANSI”.
  6. Check your text again, and you’ll see the “invincible character”.
  7. Delete it, and run your code in SQL Server again. It should work.

Meanwhile, if you can’t get Notepad++, you can paste the SQL in an online tool like “SQLiteonline”, and you’ll see the invincible characters immediately.

Conclusion

This article explained the causes of the “incorrect syntax near” error in SQL Server, and five methods that can fix it for you, depending on your use case. From everything that we’ve talked about, and what you’ve learned so far, remember the following:

  • Typographical errors and misuse of reserved keywords are the two major causes of the “incorrect syntax near” error in SQL Server.
  • Misplaced punctuation marks and unprintable characters can also cause a syntax error in SQL Server.
  • The top solution for the “incorrect syntax near” in SQL Server is to check for typographical errors, and use punctuation marks the right way.
  • If all solutions fail to solve the incorrect syntax in your SQL statements, paste the SQL in Notepad++, and enable “Encoding in ANSI”.

Right now, the incorrect syntax should be resolved in your SQL code. Take care of yourself, and always run correct and valid SQL statements on your SQL server.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

  • Ошибка incorrect table name
  • Ошибка incorrect rage multiplayer installation
  • Ошибка incorrect id 45 easyanticheat
  • Ошибка incorrect id 217
  • Ошибка incorrect expiry date