Solved

Need help with query

Posted on 2016-08-05
6
49 Views
Last Modified: 2016-08-06
Hi Expert,

This is my query in the stored procedure. When I execute it gives me error 'Invalid syntax near AND'. Any idea what is wrong.

Thanks in advance.

DECLARE @FromDate1 nchar(10)=NULL;
                  DECLARE @ToDate1 nchar(10)=NULL;
                  DECLARE @Classification1 nchar(1)=NULL;
                  SET @FromDate1 = @FromDate;
                  SET @ToDate1 = @ToDate;
                  SET @Classification1= @Classification;
                  SET @SQL='SELECT
                     U.[UserID]
                    ,ltrim(rtrim(U.[ClientUserID])) as ClientUserID
                    ,ltrim(rtrim(U.[UserFirstName])) as UserFirstName
                    ,ltrim(rtrim(U.[UserLastName])) as UserLastName
                    ,ltrim(rtrim(U.[UserAdd1])) as UserAdd1
                    ,ltrim(rtrim(U.[UserAdd2])) as UserAdd2
                    ,ltrim(rtrim(U.[UserCity])) as UserCity
                    ,ltrim(rtrim(s.[StateName])) as State
                    ,ltrim(rtrim(U.[UserZip])) as UserZip
                    ,ltrim(rtrim(U.[UserPhone])) as UserPhone
                    ,ltrim(rtrim(U.[UserEmail])) as UserEmail
                    ,ltrim(rtrim(F.StsDescription)) as UserType
                    ,ltrim(rtrim(U.[UserActive])) as UserActive
                    ,ltrim(rtrim(U.[UserStartDate])) as UserStartDate
                    ,ltrim(rtrim(FP.[StsDescription])) as Classification
                    ,ltrim(rtrim(D.[DayName])) as AttendenceDay
                    ,U.[TodaysDate],U.[AttendenceDay],U.[UserState],U.[UserType],U.[Classification]  
        
                    FROM [USERDETAILS] as U            

                    LEFT OUTER JOIN  DAYMST As D on D.DayID =U.AttendenceDay
                    LEFT OUTER JOIN  STATESMST  As S on S.StateID =U.UserState
                    LEFT OUTER JOIN  FPSCODES as F on F.StsDescription_Code=U.UserType and F.StatusCode =''UT''
                    LEFT OUTER JOIN  FPSCODES as FP on FP.StsDescription_Code=U.Classification and FP.StatusCode =''CLF''
                    where U.[UserActive] =''Y'''
             

              if @FromDate1 <> ''
                  begin
                  SET @SQL = @SQL + ' and CONVERT(DATETIME, RIGHT(UserStartDate, 4) + LEFT(UserStartDate, 4), 112) >=' + CAST(@FromDate1 AS NVARCHAR(10));
                  end

              if @ToDate1 <> ''
                  begin
                     SET @SQL = @SQL + ' and CONVERT(DATETIME, RIGHT(UserStartDate, 4) + LEFT(UserStartDate, 4), 112) <= ' + CAST(@ToDate1 AS NVARCHAR(10));
            end
             
              if @Classification1 <> ''
                  begin
                        SET @SQL = @SQL + ' and  U.[Classification] =' + CAST(@Classification1 AS NVARCHAR(1));
                  end

                  SET @SQL = @SQL + '  order by UserFirstName'
                  EXEC(@SQL)
0
Comment
Question by:RadhaKrishnaKiJaya
6 Comments
 
LVL 65

Expert Comment

by:Jim Horn
ID: 41744856
It would greatly help if you can place the above in a code block, then execute the query in SSMS, double-click on the error message, watch the cursor jump to the offending line, then tell us what line that is.

Otherwise we're guessing with a lot of code..

Also, throw in a SELECT @SQL and post that in this question.  Might make the error obvious.
0
 
LVL 26

Accepted Solution

by:
Shaun Kline earned 250 total points
ID: 41744862
Because you are using dynamic SQL, any values you use in a where clause like strings and dates need to be enclosed in two apostrophes.

As an example:
SET @SQL = @SQL + ' and CONVERT(DATETIME, RIGHT(UserStartDate, 4) + LEFT(UserStartDate, 4), 112) >=''' + CAST(@FromDate1 AS NVARCHAR(10)) + '''';

Open in new window


In this case, two apostrophes were added after the equal sign, and again after the CAST. You will need to do this throughout your dynamic SQL.
0
 
LVL 40

Assisted Solution

by:Sharath
Sharath earned 125 total points
ID: 41744971
As Shaun mentioned, you need to enclose the strings in apostrophes.
DECLARE @FromDate1 nchar(10)=NULL;
                  DECLARE @ToDate1 nchar(10)=NULL;
                  DECLARE @Classification1 nchar(1)=NULL;
                  SET @FromDate1 = @FromDate;
                  SET @ToDate1 = @ToDate;
                  SET @Classification1= @Classification;
                  SET @SQL='SELECT 
                     U.[UserID]
                    ,ltrim(rtrim(U.[ClientUserID])) as ClientUserID
                    ,ltrim(rtrim(U.[UserFirstName])) as UserFirstName
                    ,ltrim(rtrim(U.[UserLastName])) as UserLastName
                    ,ltrim(rtrim(U.[UserAdd1])) as UserAdd1
                    ,ltrim(rtrim(U.[UserAdd2])) as UserAdd2
                    ,ltrim(rtrim(U.[UserCity])) as UserCity
                    ,ltrim(rtrim(s.[StateName])) as State
                    ,ltrim(rtrim(U.[UserZip])) as UserZip
                    ,ltrim(rtrim(U.[UserPhone])) as UserPhone
                    ,ltrim(rtrim(U.[UserEmail])) as UserEmail
                    ,ltrim(rtrim(F.StsDescription)) as UserType
                    ,ltrim(rtrim(U.[UserActive])) as UserActive
                    ,ltrim(rtrim(U.[UserStartDate])) as UserStartDate
                    ,ltrim(rtrim(FP.[StsDescription])) as Classification
                    ,ltrim(rtrim(D.[DayName])) as AttendenceDay
                    ,U.[TodaysDate],U.[AttendenceDay],U.[UserState],U.[UserType],U.[Classification]  
        
                    FROM [USERDETAILS] as U             

                    LEFT OUTER JOIN  DAYMST As D on D.DayID =U.AttendenceDay
                    LEFT OUTER JOIN  STATESMST  As S on S.StateID =U.UserState
                    LEFT OUTER JOIN  FPSCODES as F on F.StsDescription_Code=U.UserType and F.StatusCode =''UT''
                    LEFT OUTER JOIN  FPSCODES as FP on FP.StsDescription_Code=U.Classification and FP.StatusCode =''CLF''
                    where U.[UserActive] =''Y'''
             

              if @FromDate1 <> ''
                  begin
                  SET @SQL = @SQL + ' and CONVERT(DATETIME, RIGHT(UserStartDate, 4) + LEFT(UserStartDate, 4), 112) >=''' + CAST(@FromDate1 AS NVARCHAR(10)) + '''';
                  end

              if @ToDate1 <> ''
                  begin
                     SET @SQL = @SQL + ' and CONVERT(DATETIME, RIGHT(UserStartDate, 4) + LEFT(UserStartDate, 4), 112) <= ''' + CAST(@ToDate1 AS NVARCHAR(10)) + '''';
            end
              
              if @Classification1 <> ''
                  begin
                        SET @SQL = @SQL + ' and  U.[Classification] =''' + CAST(@Classification1 AS NVARCHAR(1)) + '''';
                  end

                  SET @SQL = @SQL + '  order by UserFirstName'
                  EXEC(@SQL)

Open in new window

0
Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

 
LVL 48

Assisted Solution

by:PortletPaul
PortletPaul earned 125 total points
ID: 41745073
this is what your code generates (after the select clause):
FROM [USERDETAILS] AS U

      LEFT OUTER JOIN DAYMST AS D ON D.DayID = U.AttendenceDay
      LEFT OUTER JOIN STATESMST AS S ON S.StateID = U.UserState
      LEFT OUTER JOIN FPSCODES AS F ON F.StsDescription_Code = U.UserType AND F.StatusCode = 'UT'
      LEFT OUTER JOIN FPSCODES AS FP ON FP.StsDescription_Code = U.Classification AND FP.StatusCode = 'CLF'
WHERE U.[UserActive] = 'Y'
AND CONVERT(datetime, RIGHT(UserStartDate, 4) + LEFT(UserStartDate, 4), 112) >= 20160101
AND CONVERT(datetime, RIGHT(UserStartDate, 4) + LEFT(UserStartDate, 4), 112) <= 20160701
ORDER BY UserFirstName

Open in new window

Notice how there are no quotation marks around the 20160101 or 20160701

If you keep using NCHAR(10)  however you are going to have trouble using date style 112 which is 8 characters long. If you just add the extra commas you are then going to get 2 trailing spaces

where U.[UserActive] ='Y' and CONVERT(DATETIME, RIGHT(UserStartDate, 4) + LEFT(UserStartDate, 4), 112) >='20160101  '


This is what I suggest. Note this is just ends in a select of @sql, so you can see what it produces. Also note I have added some declares so it runs as is.
NCHAR(10) is changed to NCHAR(8)  to suit date strings in YYYYMMDD format (or just use varchar(10) directly when declaring them)
declare @SQL nvarchar(max)
DECLARE @FromDate nchar(8) = '20160101'
DECLARE @FromDate1 nchar(8) = '20160101'
DECLARE @ToDate nchar(8) = '20160701'
DECLARE @ToDate1 nchar(8) = '20160701'
DECLARE @Classification nchar(1) = NULL
DECLARE @Classification1 nchar(1) = NULL
SET @SQL = 'SELECT 
                     U.[UserID]
                    ,ltrim(rtrim(U.[ClientUserID])) as ClientUserID
                    ,ltrim(rtrim(U.[UserFirstName])) as UserFirstName
                    ,ltrim(rtrim(U.[UserLastName])) as UserLastName
                    ,ltrim(rtrim(U.[UserAdd1])) as UserAdd1
                    ,ltrim(rtrim(U.[UserAdd2])) as UserAdd2
                    ,ltrim(rtrim(U.[UserCity])) as UserCity
                    ,ltrim(rtrim(s.[StateName])) as State
                    ,ltrim(rtrim(U.[UserZip])) as UserZip
                    ,ltrim(rtrim(U.[UserPhone])) as UserPhone
                    ,ltrim(rtrim(U.[UserEmail])) as UserEmail
                    ,ltrim(rtrim(F.StsDescription)) as UserType
                    ,ltrim(rtrim(U.[UserActive])) as UserActive
                    ,ltrim(rtrim(U.[UserStartDate])) as UserStartDate
                    ,ltrim(rtrim(FP.[StsDescription])) as Classification
                    ,ltrim(rtrim(D.[DayName])) as AttendenceDay
                    ,U.[TodaysDate],U.[AttendenceDay],U.[UserState],U.[UserType],U.[Classification]  
        
                    FROM [USERDETAILS] as U             

                    LEFT OUTER JOIN  DAYMST As D on D.DayID =U.AttendenceDay
                    LEFT OUTER JOIN  STATESMST  As S on S.StateID =U.UserState
                    LEFT OUTER JOIN  FPSCODES as F on F.StsDescription_Code=U.UserType and F.StatusCode =''UT''
                    LEFT OUTER JOIN  FPSCODES as FP on FP.StsDescription_Code=U.Classification and FP.StatusCode =''CLF''
                    where U.[UserActive] =''Y'''


IF @FromDate1 <> ''
BEGIN
      --SET @SQL = @SQL + ' and CONVERT(DATETIME, RIGHT(UserStartDate, 4) + LEFT(UserStartDate, 4), 112) >=' + CAST(@FromDate1 AS nvarchar(10));
      SET @SQL = @SQL + ' and CONVERT(DATETIME, RIGHT(UserStartDate, 4) + LEFT(UserStartDate, 4), 112) >=''' + @FromDate1 + ''''
END

IF @ToDate1 <> ''
BEGIN
      --SET @SQL = @SQL + ' and CONVERT(DATETIME, RIGHT(UserStartDate, 4) + LEFT(UserStartDate, 4), 112) <= ' + CAST(@ToDate1 AS nvarchar(10));
      SET @SQL = @SQL + ' and CONVERT(DATETIME, RIGHT(UserStartDate, 4) + LEFT(UserStartDate, 4), 112) >=''' + @ToDate1 + ''''
END

IF @Classification1 <> ''
BEGIN
      SET @SQL = @SQL + ' and  U.[Classification] =' + CAST(@Classification1 AS nvarchar(1));
END

SET @SQL = @SQL + '  order by UserFirstName'
--EXEC (@SQL)
SELECT
      @sql

Open in new window

here is the result (but I did reformat it)
SELECT
      U.[UserID]
    , LTRIM(RTRIM(U.[ClientUserID]))    AS ClientUserID
    , LTRIM(RTRIM(U.[UserFirstName]))   AS UserFirstName
    , LTRIM(RTRIM(U.[UserLastName]))    AS UserLastName
    , LTRIM(RTRIM(U.[UserAdd1]))        AS UserAdd1
    , LTRIM(RTRIM(U.[UserAdd2]))        AS UserAdd2
    , LTRIM(RTRIM(U.[UserCity]))        AS UserCity
    , LTRIM(RTRIM(s.[StateName]))       AS State
    , LTRIM(RTRIM(U.[UserZip]))         AS UserZip
    , LTRIM(RTRIM(U.[UserPhone]))       AS UserPhone
    , LTRIM(RTRIM(U.[UserEmail]))       AS UserEmail
    , LTRIM(RTRIM(F.StsDescription))    AS UserType
    , LTRIM(RTRIM(U.[UserActive]))      AS UserActive
    , LTRIM(RTRIM(U.[UserStartDate]))   AS UserStartDate
    , LTRIM(RTRIM(FP.[StsDescription])) AS Classification
    , LTRIM(RTRIM(D.[DayName]))         AS AttendenceDay
    , U.[TodaysDate]
    , U.[AttendenceDay]
    , U.[UserState]
    , U.[UserType]
    , U.[Classification]

FROM [USERDETAILS] AS U

      LEFT OUTER JOIN DAYMST AS D ON D.DayID = U.AttendenceDay
      LEFT OUTER JOIN STATESMST AS S ON S.StateID = U.UserState
      LEFT OUTER JOIN FPSCODES AS F ON F.StsDescription_Code = U.UserType
                  AND F.StatusCode = 'UT'
      LEFT OUTER JOIN FPSCODES AS FP ON FP.StsDescription_Code = U.Classification
                  AND FP.StatusCode = 'CLF'
WHERE U.[UserActive] = 'Y'
      AND CONVERT(datetime, RIGHT(UserStartDate, 4) + LEFT(UserStartDate, 4), 112) >= '20160101'
      AND CONVERT(datetime, RIGHT(UserStartDate, 4) + LEFT(UserStartDate, 4), 112) >= '20160701'
ORDER BY
      UserFirstName

Open in new window

{+ edit} look at lines 44 and 45 of the suggested query, forgot to change the >= to <=
0
 
LVL 48

Expert Comment

by:PortletPaul
ID: 41745081
I just came across a previous related question
https://www.experts-exchange.com/questions/28961789/Need-help-with-a-query.html

Your column [UserStartDate] is a string (char or varchar) in mmddyyyy format

Storing dates as strings always a bad idea and I suggest you look at this:

https://www.experts-exchange.com/articles/1499/DATE-and-TIME-don't-be-scared-and-do-it-right-the-first-time.html
0
 

Author Closing Comment

by:RadhaKrishnaKiJaya
ID: 41745683
Thank you very much everybody for helping me.
0

Featured Post

How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

860 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question