Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Need help with query

Posted on 2016-08-05
6
Medium Priority
?
63 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 66

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 27

Accepted Solution

by:
Shaun Kline earned 1000 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 41

Assisted Solution

by:Sharath
Sharath earned 500 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 49

Assisted Solution

by:PortletPaul
PortletPaul earned 500 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 49

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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

886 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