Solved

Need help with query

Posted on 2016-08-05
6
42 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
Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

 
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

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…

932 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now