Conversion error in SQL Server - sql-server

I have the following SQL query that gets a date (one parameter of start date and end date separated by a comma) as a parameter and should returns all values between these dates.
(Long query - I'm posting just the relevant part)
Set #SQLQuery = #SQLQuery + 'And (o.Date >= LEFT(''' + #Date + ''', charindex('','',''' + #Date+ ''') - 1)'
+ ' AND o.Date <= RIGHT(''' + #Date + ''', charindex('','',''' + #Date+ ''') - 1)) '
The format of the date parameter is:
start date,end date in MM,DD,YYYY format
When the date parameter is for example: 8-5-2015,08-9-2016 it's working perfectly, but when it is for example 8-5-2015,08-11-2016 I'm getting the following error:
Conversion failed when converting date and/or time from character
string
I think it's related to the two digits on the days part.
Any idea what can causes that?

It seems to be problem with logic inside Right function. Please use below logic , i have added length function to find right date correctly.
Set #SQLQuery = #SQLQuery + 'And (o.Date >= LEFT(''' + #Date + ''', charindex('','',''' + #Date+ ''') - 1)'
+ ' AND o.Date <= RIGHT(''' + #Date + ''', len(''' + #Date+ ''') - charindex('','',''' + #Date+ '''))) '

change the query to following type:
Set #SQLQuery = #SQLQuery + 'And (o.Date >= LEFT(''' + #Date + ''', charindex('','',''' + #Date+ ''') - 1)'
+ ' AND o.Date <= RIGHT(''' + #Date + ''', LEN(''' + #Date+ ''') - charindex('','',''' + #Date+ '''))) '

Related

SQL dynamic query check for null, or empty string parameter

I am writing a stored procedure that will be executed from an SSRS report. It receives 2 parameters: SourceID, and ConfirmationNumber but it is not working for all the tests that I am running
this returns recs:[dbo].[GetParkingPaymentInformation] 'PARC', ''
this does not return recs:[dbo].[GetParkingtPaymentInformation] 'PARC', NULL
this does not return recs:[dbo].[GetParkingPaymentInformation] '', '002077770'
this does not return recs:[dbo].[GetParkingPaymentInformation] NULL, '002077770'
this does return recs:[dbo].[GetParkingPaymentInformation] 'PARC', '002077770'
I want the sp to work when one or the other parameter are either null, or blank.
This is what I have so far for code:
SET #s_SQL = 'SELECT d.ID, d.TransactionNumber, h.SourceType, ' + #s_ColumnName + ', d.FirstName, d.LastName,' +
'LTRIM(RTRIM(d.FirstName)) + '' '' + LTRIM(RTRIM(d.LastName)) [Name], '+
'd.PaymentAmount, CONVERT(VARCHAR(10), CAST(d.InitiationDate AS DATE), 101) [InitiationDate]' +
', d.Fee, d.TotalAmount, d.PaymentStatus, d.PaymentType, d.CreditCardType, ' +
'CONVERT(VARCHAR(10), CAST(d.PaymentEffectiveDate AS DATE), 101) [PaymentEffectiveDate]' +
', CONVERT(VARCHAR(10), CAST(d.ProcessDate AS DATE), 101) [ProcessDate], CONVERT(VARCHAR(10), CAST(d.CreatedDate AS DATE), 101) [CreatedDate],' +
'd.CashCode, d.TransConfirmID' +
', d.Phone, d.StreetAddress1, d.StreetAddress2, ' +
'LTRIM(RTRIM(d.StreetAddress1)) + '' '' + CASE WHEN LEN(d.StreetAddress2) > 0 THEN LTRIM(RTRIM(d.StreetAddress2)) ELSE '''' END [Address]' +
', d.City, d.[State], d.ZipFive, d.ZipFour, d.Email ' +
'FROM '+ #s_TableHeader + ' h WITH (NOLOCK) ' +
'INNER JOIN ' + #s_TableDetail + ' d WITH (NOLOCK) ' +
'ON h.ID = d.headerID ' +
'WHERE' +
' ((h.sourcetype = ' + '''' + #s_Source_Type + '''' + ') OR ' + '''' + #s_Source_Type + '''' + ' IS NULL OR ' + '''' + #s_Source_Type + '''' + '= '''')' +
' AND ((d.transconfirmid = ' + '''' + #s_Confirmation_Number + '''' + ') OR ' + '''' + #s_Confirmation_Number + '''' + ' IS NULL OR ' + '''' + #s_Confirmation_Number + '''' + '= '''')'
Any help I can get to figure why my checks are not working, it would be great.
*Please note that your example sql code is incomplete and that you name the parameters slightly different from the variables which makes for difficulty understanding the question. *
It is not without reason that the use of dynamic sql is discouraged even in cases where the dangers of sql injection are negligible. One of the primary reasons for this is that dynamic sql is difficult to write, read and debug. That being said I have often found myself using it to solve for problems within poorly designed systems.
I assume that you have investigated alternatives appropriately.
To reduce the complexity of dynamic sql statements I have found that constructing the statement in a modular way to be a good strategy.
In your particular case the use of an 'if' statement (or some variation) may help reduce the complexity of your dynamic where clause and likely help resolve your problem.
Example:
`
set #sql = 'select....... your select statement..... where'
if (#a_Source_Type is not null and len(#a_Source_Type) > 0)
begin
set #sql += '''' + #a_Source_Type + ''' = some_field and '
end
else
begin
set #sql += ' len(isnull(some_field, '''')) = 0 and '
end
set #sql += ' 1 = 1 '
`
The above attempts to move the comparison operators out of the dynamic sql.
I suggest refactoring your query to use a strategy similar to this example as you may find it easier to identify erroneous code.
the final line of the example has proven useful in circumstances where the resulting dynamic sql statement may or may not have where clauses to append
Try changing your WHERE to something like this:
'where' +
' h.sourcetype = ' + isnull(quotename(nullif(#s_Source_Type, ''), ''''), 'h.sourcetype') +
' AND d.transconfirmid = ' + isnull(quotename(nullif(#s_Confirmation_Number, ''), ''''), 'd.transconfirmid')

Stored Procedure - Error converting data type varchar to float

I am trying to insert a float value from one table into another, but am getting the error in the subject line of this post:
Error converting data type varchar to float.
Both fields in both tables are set to float. Values are latitudes and longitudes for zip codes. An example of a latitude/longitude would be:
45.895698
-72.365896
Here is a few snippets of my code:
declare #v_latitude float
declare #v_longitude float
-- Grab Latitude & Longitude --
if #v_zip_code IS NOT NULL
SELECT #v_latitude=z_latitude, #v_longitude=z_longitude FROM tbl_ZipCodes WHERE z_zip_code = #v_zip_code
set #strValues = #strValues + '''' + #v_city + ''', ''' + #v_state + ''', ''' + #v_zip_code + ''', ''' + #v_daytime_phone + ''', ''' + #v_contact_name + ''', '''
+ #v_email_address + ''', ' + cast(#u_id as varchar) + ', ' + cast(#d_id as varchar) + ', 1, ''' + cast(CURRENT_TIMESTAMP as varchar) + ''', 1 , ''' + cast(#v_latitude as float) + ''', ''' + cast(#v_longitude as float) + ''', '''
+ cast(CURRENT_TIMESTAMP as varchar) + ''', dft.df_t_id, (SELECT CASE WHEN dft.df_t_v_price <> 0 THEN dft.df_t_v_price WHEN dft.df_t_v_internet_price <> 0 THEN dft.df_t_v_internet_price WHEN dft.df_t_v_other_price <> 0 THEN dft.df_t_v_other_price ELSE 0 END AS v_search_price)'
The part of the code that uses the #v_latitude and #v_longitude variables is here:
... , ''' + cast(#v_latitude as float) + ''', ''' + cast(#v_longitude as float) + ''', ...
Ignore the "..." as I am demonstrating there is additional code that surrounds those values.
Any help would be appreciated!
Edit: Here is additional code I am using:
-- Check For User Profile --
SELECT #counter = COUNT(*) FROM tbl_Customers WHERE u_id = #u_id
if #counter > 0
SELECT #v_city=c_city, #v_state =c_state, #v_zip_code=c_zip_code,#v_daytime_phone =c_phone_number FROM tbl_Customers WHERE u_id = #u_id
else
SELECT #v_city=d_city, #v_state =d_state, #v_zip_code=d_zip_code,#v_daytime_phone =d_phone_number FROM tbl_Dealers WHERE d_id = #d_id
-- Grab Contact Information --
SELECT #v_contact_name = u_name, #v_email_address = u_email_address FROM tbl_Users WHERE u_id = #u_id
-- Grab Latitude & Longitude --
if #v_zip_code IS NOT NULL
SELECT #v_latitude=z_latitude, #v_longitude=z_longitude FROM tbl_ZipCodes WHERE z_zip_code = #v_zip_code
-- Add Additional Fields --
set #strFields = #strFields + 'v_city, v_state, v_zip_code, v_daytime_phone, v_contact_name, v_email_address, u_id, d_id, v_processed, v_processed_date, v_active, ,v_latitude, v_longitude, v_last_activity, v_dealerfeed, v_search_price'
set #strJoin = #strJoin + ' LEFT JOIN tbl_Vehicles v ON v.v_stock_number = dft.df_t_v_stock_number'
set #strValues = #strValues + '''' + #v_city + ''', ''' + #v_state + ''', ''' + #v_zip_code + ''', ''' + #v_daytime_phone + ''', ''' + #v_contact_name + ''', '''
+ #v_email_address + ''', ' + cast(#u_id as varchar) + ', ' + cast(#d_id as varchar) + ', 1, ''' + cast(CURRENT_TIMESTAMP as varchar) + ''', 1 , ''' + #v_latitude + ''', ''' + #v_longitude + ''', '''
+ cast(CURRENT_TIMESTAMP as varchar) + ''', dft.df_t_id, (SELECT CASE WHEN dft.df_t_v_price <> 0 THEN dft.df_t_v_price WHEN dft.df_t_v_internet_price <> 0 THEN dft.df_t_v_internet_price WHEN dft.df_t_v_other_price <> 0 THEN dft.df_t_v_other_price ELSE 0 END AS v_search_price)'
-- Insert Records Into Vehicle Table (but not twice!) --
set #strSQL = 'INSERT INTO tbl_Vehicles (' + #strFields + ') SELECT ' + #strValues + ' FROM tbl_DealerFeed_temp dft ' + #strJoin + ' WHERE dft.df_t_processed = 0 AND dft.df_d_id = ' + cast(#df_d_id as varchar)
set #strSQL = #strSQL + ' AND dft.df_t_v_stock_number NOT IN ( SELECT v.v_stock_number FROM tbl_Vehicles v WHERE v.d_id = ' + cast(#d_id as varchar) + ')'
print #strSQL
EXEC (#strSQL)
The problem probably is the fact that your dynamic sql is putting single quotes around the float.
Try changing
, ''' + cast(#v_latitude as float) + ''', ''' + cast(#v_longitude as float) + ''', ..
into
, ' + STR(#v_latitude,<length>,<decimals>) + ', ' + STR(#v_longitude,<length>,<decimals>) + ', ..
See STR () for reference
As you're doing dynamic SQL you force everything down to a string type.
But it's the single quotes that are tripping you up. If the column you're inserting into is a float you don't want your float value on the insert wrapped in quotes.
Also I find CONVERT is a little more flexible (with dates mostly) than CAST (I've only done CONVERT for diversity):
so you want get rid of those triple quotes:
...+ CONVERT(varchar(20), #v_latitude) +',' + CONVERT(varchar(20), #v_longitude) +...
Edited to add: your fixed code should look like this:
set #strValues = #strValues + '''' + #v_city + ''', ''' + #v_state + ''', ''' + #v_zip_code + ''', ''' + #v_daytime_phone + ''', ''' + #v_contact_name + ''', '''
+ #v_email_address + ''', ' + cast(#u_id as varchar) + ', ' + cast(#d_id as varchar) + ', 1, ''' + cast(CURRENT_TIMESTAMP as varchar) + ''', 1 , ' + Convert(varchar(20), #v_latitude) + ', ' + Convert(varchar(20), #v_longitude) + ', '''
+ cast(CURRENT_TIMESTAMP as varchar) + ''', dft.df_t_id, (SELECT CASE WHEN dft.df_t_v_price <> 0 THEN dft.df_t_v_price WHEN dft.df_t_v_internet_price <> 0 THEN dft.df_t_v_internet_price WHEN dft.df_t_v_other_price <> 0 THEN dft.df_t_v_other_price ELSE 0 END AS v_search_price)'
Execute your SQL without the EXEC (#strSQL) and have a look at the printed SQL
Edited again; to fix your Float being limited to being rounded to 4 decimal places (this is down to it being a Float) but you can get around it by converting it to a decimal first or using STR, this'll help you understand what's happening:
declare #v_latitude float = -45.12345678
print #v_latitude
print 'Cast = '+ cast( #v_latitude as varchar)
print 'Convert = '+ convert(varchar(20), #v_latitude)
print 'Cast via decimal = '+ cast( cast(#v_latitude as decimal(18,9)) as varchar)
print 'Convert via decimal = '+ convert( varchar(20), convert(decimal(18,9), #v_latitude))
print 'str = '+ str(#v_latitude,18,9)
==
-45.1235
Cast = -45.1235
Convert = -45.1235
Cast via decimal = -45.123456780
Convert via decimal = -45.123456780
str = -45.123456780
you can try
''' + cast( #v_latitude as varchar(20))
+ ''', ''' + cast((#v_longitude as varchar(20))+ '''

Compile error - Dynamic SQL

I've tried to implement some dynamic SQL to create a cursor as an extension of a simple SELECT query. The cursor is used as a way to print the GROUPED values returned from the SELECT as a message in SQL Server Management Studio (kind of like a visual summary of the data) . The purpose of this approach is half task related and half to benefit my understanding of how dynamic SQL can be developed. Code reads:
DECLARE #Focus VARCHAR(10);
SET #Focus = 'Completed'; /* User input event focus {Started, Completed} */
DECLARE #PeriodStartDate DATE, #PeriodEndDate DATE;
SET #PeriodStartDate = '04/01/2014';
SET #PeriodEndDate = GETDATE();
DECLARE #sql VARCHAR(MAX);
SET #sql =
'SELECT ' +
'CASE DATEPART(M, ' + '[Event ' + CASE #Focus
WHEN 'Started' THEN 'Start'
WHEN 'Completed' THEN 'End'
END + ' Date]) ' +
' WHEN 1 THEN ''January'' ' +
' WHEN 2 THEN ''February'' ' +
' WHEN 3 THEN ''March'' ' +
' WHEN 4 THEN ''April'' ' +
' WHEN 5 THEN ''May'' ' +
' WHEN 6 THEN ''June'' ' +
' WHEN 7 THEN ''July'' ' +
' WHEN 8 THEN ''August'' ' +
' WHEN 9 THEN ''September'' ' +
' WHEN 10 THEN ''October'' ' +
' WHEN 11 THEN ''November'' ' +
' WHEN 12 THEN ''December'' ' +
' END AS [Event ' + #Focus + ' Month], ' +
' COUNT([Unique ID]) AS [Number of Events] ' +
' FROM [udf_Events](' + #Focus + ', ' + CAST(#PeriodStartDate AS VARCHAR) + ', ' + CAST(#PeriodEndDate AS VARCHAR) + ') ' +
' GROUP BY ' +
' DATEPART(M, ' + '[Event ' + CASE #Focus
WHEN 'Started' THEN 'Start'
WHEN 'Completed' THEN 'End'
END + ' Date]) ' +
' ORDER BY ' +
' DATEPART(M, ' + '[Event ' + CASE #Focus
WHEN 'Started' THEN 'Start'
WHEN 'Completed' THEN 'End'
END + ' Date]) '
;
DECLARE Results CURSOR
FOR
SELECT
#sql;
The error message I receive:
Msg 16924, Level 16, State 1, Line 71 Cursorfetch: The number of
variables declared in the INTO list must match that of selected
columns.
Through grappling with the problem and trying to execute the query as a SELECT statement (removing the complexity of the cursor) using EXEC(#sql) the error message reads:
Invalid column name 'Completed'.
..Which leads me to believe the problem lies with the CASE expression in the first field selected. udf_Events is an in-line table valued function with three arguments. Amongst others, it has columns [Event Start Date] and [Event End Date] which are the values the cursor is looking to do its work on.
Try this...few ' were missing in your query
DECLARE #Focus VARCHAR(10);
SET #Focus = 'Completed'; /* User input event focus {Started, Completed} */
DECLARE #temp VARCHAR(500);
IF(#Focus = 'Completed')
SET #temp = '[Event End Date]'
ELSE
SET #temp = '[Event Start Date]'
DECLARE #PeriodStartDate DATE, #PeriodEndDate DATE;
SET #PeriodStartDate = '04/01/2014';
SET #PeriodEndDate = GETDATE();
DECLARE #sql VARCHAR(MAX);
SET #sql =
'SELECT ' +
'CASE DATEPART(M, ' + #temp + ')' +
' WHEN 1 THEN ''January'' ' +
' WHEN 2 THEN ''February'' ' +
' WHEN 3 THEN ''March'' ' +
' WHEN 4 THEN ''April'' ' +
' WHEN 5 THEN ''May'' ' +
' WHEN 6 THEN ''June'' ' +
' WHEN 7 THEN ''July'' ' +
' WHEN 8 THEN ''August'' ' +
' WHEN 9 THEN ''September'' ' +
' WHEN 10 THEN ''October'' ' +
' WHEN 11 THEN ''November'' ' +
' WHEN 12 THEN ''December'' ' +
' END AS [Event ' + #Focus + ' Month], ' +
' COUNT([Unique ID]) AS [Number of Events] ' +
' FROM [udf_Events](''' + #Focus + ''', ''' + CAST(#PeriodStartDate AS VARCHAR) + ''', ''' + CAST(#PeriodEndDate AS VARCHAR) + ''') ' +
' GROUP BY ' +
' DATEPART(M, ' + #temp + ')' +
' ORDER BY ' +
' DATEPART(M, ' + #temp + ')';
print #sql
You're not quoting the dates in the call to udf_Events so you end up with
[udf_Events](Completed, 2014-04-01, 2014-09-19)
instead of
[udf_Events](Completed, '2014-04-01', '2014-09-19')
The fix is to change the line
' FROM [udf_Events](' + #Focus + ', ' + CAST(#PeriodStartDate AS VARCHAR) + ', ' + CAST(#PeriodEndDate AS VARCHAR) + ') ' +
to
' FROM [udf_Events](' + #Focus + ', ''' + CAST(#PeriodStartDate AS VARCHAR) + ''', ''' + CAST(#PeriodEndDate AS VARCHAR) + ''') ' +
That said, if the parameters to udf_Events are datetimes then I would consider changing the format to YYYYMMDD as this is unambiguous. To do this you can use CONVERT(char(8), <date>, 112) where <date> is the date to be converted.
i.e:
' FROM [udf_Events](' + #Focus + ', ''' + CONVERT(char(8), #PeriodStartDate, 112) + ''', ''' + CONVERT(char(8), #PeriodEndDate, 112) + ''') ' +

CAST varchar to datetime in dynamic SQL

I keep getting the following error:
Msg 241, Level 16, State 1, Line 9 Conversion failed when converting
datetime from character string.
Here is the code I am trying to execute:
DECLARE #v_sql varchar(max),
#v_database varchar(25),
#vStartTime DATETIME,
#vEndTime DATETIME
SELECT #v_database = N'[DATABASE_NAME]', #vStartTime = '2012-09-27', #vEndTime = '2012-11-27'
SELECT #v_sql = N'SELECT
(SELECT ID FROM DATASTORE.DBO.PLANT WHERE DESCRIPTION = ''Henderson''),
SEQ,
AID,
NAME,
GRP,
AREA,
PRIO,
CASE ITIME WHEN ''-'' THEN NULL ELSE CAST(SUBSTRING(ITIME,1,8) + '' '' + SUBSTRING(ITIME,9,2) + '':'' + SUBSTRING(ITIME,11,2) + '':'' + SUBSTRING(ITIME,13,2) AS DATETIME) END ITIME,
CASE ATIME WHEN ''-'' THEN NULL ELSE CAST(SUBSTRING(ATIME,1,8) + '' '' + SUBSTRING(ATIME,9,2) + '':'' + SUBSTRING(ATIME,11,2) + '':'' + SUBSTRING(ATIME,13,2) AS DATETIME) END ATIME,
CASE NTIME WHEN ''-'' THEN NULL ELSE CAST(SUBSTRING(NTIME,1,8) + '' '' + SUBSTRING(NTIME,9,2) + '':'' + SUBSTRING(NTIME,11,2) + '':'' + SUBSTRING(NTIME,13,2) AS DATETIME) END NTIME,
DUR,
MSG,
VAR1,
VAR2,
VAR3,
VAR4,
OPR,
USER_COMMENT
FROM ' + #v_database + '.PROD.ALARM
WHERE CAST(substring(ITIME, 1, 4) + ''-'' + substring(ITIME, 5, 2) + ''-'' + substring(ITIME, 7, 2) + '' '' + substring(ITIME,9,2) + '':'' + substring(ITIME,11,2) + '':'' + substring(ITIME,13,2) + substring(ITIME,15,3) AS DATETIME) BETWEEN ' + #vStartTime +' AND ' + #vEndTime + ' ORDER BY ITIME'
EXEC(#v_sql)
Any help would be much appreciated, I am looking into this for a co-worker and it's got us both stumped.
Edit with a bit more digging, we were able to resolve it ourselves, passing parameters to sp_executesql:
declare
#vSql NVARCHAR(MAX),
#vParam NVARCHAR(MAX),
#vDatabase VARCHAR(15)
SET #vParam = '#vStartTime DATETIME, #vEndTime DATETIME'
SELECT #vSql = '
SELECT ''
'+ #vDatabase + ''',
ITEM_CODE,
SOURCE,
DEST,
TRAN_DT,
MILL_NAME,
NULL
FROM ' + #vDatabase + '.PROD.GRD_LOG
WHERE TRAN_DT BETWEEN #vStartTime AND #vEndTime'
EXEC sp_executesql #vSql, #vParam, #vStartTime, #vEndTime
By making the variables NVARCHAR(MAX), and then using sp_executesql instead of just executing the #vSql variable, we were able to resolve our issue.
Thanks to anyone who might have been looking into this.
In your original dynamic SQL, you were trying to add datetime variable to a text string which results in SQL attempting to convert the text string to a datetime value (by the order of precedence of conversion). You need to set the variables to nvarchar as well to avoid conversion in the original dynamic SQL.

Stored Procedure with a conditional?

I trying to rewrite a stored procedure and my SQL is not very good. What i'm hoping to do is write it so that if ModuleID is 555 then select a custom date range (eg. 2012-01-01 2012-12-31). The Current SP is below.
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
/*** EventsGetByRange ***/
ALTER PROCEDURE [dbo].[EventsGetByRange]
(
#Filter nvarchar(500),
#BeginDate datetime,
#EndDate datetime
)
AS
SET DATEFORMAT mdy
Declare #sql nvarchar(4000)
Select #sql = 'SELECT E.PortalID, E.EventID, E.RecurMasterID, E.ModuleID, E.EventDateBegin, E.EventDateEnd, '
+ 'E.EventTimeBegin, E.Duration, E.EventName, E.EventDesc, '
+ 'E.Importance, E.CreatedDate, '
+ 'CreatedBy = U.DisplayName, '
+ 'CreatorID = E.CreatedBy, '
+ 'E.Every, '
+ 'E.Period, '
+ 'E.RepeatType, '
+ 'E.Notify, '
+ 'E.approved, '
+ 'E.Signups, '
+ 'E.MaxEnrollment, '
+ '(Select count(*) from dbo.EventsSignups WHERE EventID = E.EventID and E.Signups = 1) as Enrolled, '
+ 'E.EnrollRoleID, '
+ 'E.EnrollFee, '
+ 'E.EnrollType, '
+ 'E.PayPalAccount, '
+ 'E.PayPalPassword, '
+ 'E.Cancelled, '
+ 'E.DetailPage, '
+ 'E.DetailNewWin, '
+ 'E.DetailURL, '
+ 'E.ImageURL, '
+ 'E.ImageType, '
+ 'E.ImageWidth, '
+ 'E.ImageHeight, '
+ 'E.ImageDisplay, '
+ 'E.Location, '
+ 'c.LocationName, '
+ 'c.MapURL, '
+ 'E.Category, '
+ 'b.CategoryName, '
+ 'b.Color, '
+ 'b.FontColor, '
+ 'E.Reminder, '
+ 'E.TimezoneOffset, '
+ 'E.SendReminder, '
+ 'E.ReminderTime, '
+ 'E.ReminderTimeMeasurement, '
+ 'E.ReminderFrom, '
+ 'E.SearchSubmitted, '
+ 'E.CustomField1, '
+ 'E.CustomField2, '
+ 'E.EnrollListView, '
+ 'E.DisplayEndDate, '
+ 'E.AllDayEvent, '
+ 'E.OwnerID, '
+ 'OwnerName = O.DisplayName, '
+ 'E.LastUpdatedAt, '
+ 'LastUpdatedBy = L.DisplayName, '
+ 'E.LastUpdatedID, '
+ '(Select ModuleTitle from dbo.Modules WHERE ModuleID = E.ModuleID) as ModuleTitle, '
+ 'RMOwnerID = r.OwnerID, '
+ 'r.RRULE, '
+ 'E.OriginalDateBegin, '
+ 'E.NewEventEmailSent '
+ 'FROM dbo.Events E '
+ 'inner join dbo.EventsRecurMaster AS r on E.RecurMasterID = r.RecurMasterID '
+ 'left outer join dbo.Users U on E.CreatedBy = U.UserID '
+ 'left outer join dbo.Users O on E.OwnerID = O.UserID '
+ 'left outer join dbo.Users L on E.LastUpdatedID = L.UserID '
+ 'left join dbo.EventsCategory b on E.Category = b.Category '
+ 'left join dbo.EventsLocation c on E.Location = c.Location '
+ 'WHERE (E.ModuleID = 555 AND E.EventTimeBegin BETWEEN 2012-01-01 AND 2012-12-31) OR ((E.EventTimeBegin <= DATEADD(DAY,1,''' + convert(varchar, #EndDate) + ''') AND DATEADD(minute,E.Duration,E.EventTimeBegin) >= ''' + convert(varchar, #BeginDate) + ''') OR '
+ ' (E.EventTimeBegin BETWEEN ''' + convert(varchar, #BeginDate) + ''' AND DATEADD(DAY,1,''' + convert(varchar, #EndDate) + ''')))'
+ ' AND E.Approved = 1'
+ ' AND E.Cancelled = 0'
+ ' ' + #Filter + ' '
+ ' ORDER BY E.EventDateBegin, E.EventTimeBegin, E.EventDateEnd'
EXEC (#sql)
UPDATE: I used the where statemnnt that Diego recommended but that is not having the desired result. It does not act as and If\Else scanrio (which makes sense when I think about it).
I need to first identify if the module ID is 555 and if so only pull the dates from in the hard coded range otherwise execute it as written. Please let me know if more detail is required.
is the proc failing?
did you try adding E.ModuleID = 555 on the where clause?
Do you really want to hard code the value 555? how about passing it
on a parameter?
And most important question: why adding the sql statement to a
variable and execute it? why not just run the SQL? Is it because of
the #Filter variable?
also, sql server 2005 or 2008?
why nvarchar and not varchar on your variables ("n" occupies double
of space)
EDIT:
ok, you have a OR in there so it may be tricky. Do you want everything from code 555 despite the date range value, or everything within the date range and code 555?
I assume option 2 would make more sense so just add
E.ModuleID = 555
before the
+ ' AND E.Approved = 1'

Resources