Solved

Need help with query

Posted on 2016-08-05
6
39 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
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
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 to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

708 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

16 Experts available now in Live!

Get 1:1 Help Now