Solved

Need help with query

Posted on 2016-08-05
6
58 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 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 41

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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 49

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 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

Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

Question has a verified solution.

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

This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
I have a large data set and a SSIS package. How can I load this file in multi threading?
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 INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

622 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