I am trying to insert into a table with dynamic sql with the following code:
SET #SQLINSERT = 'INSERT INTO ' + #TABLENAME + ' (OP__DOCID, OP__PARENTID, OP__FOLDERID, CLIENTKEY, ADMISSIONKEY, PGMKEY, ' +
'PGMADMISSIONKEY, STAFFKEY, GroupSize, MealTime, AppMgrKey, SessionNum, FacilityKey, TtmNoteText,' + #DATEFIELD + ', ' + #TIMEFIELD + ') '
SET #SQLVALUES = 'VALUES (' + CAST(#NEWDOCID AS VARCHAR) + ', ' + CAST(#CLIENTKEY AS VARCHAR) + ', ' +
CAST(#CLIENTKEY AS VARCHAR) + ', ' + CAST(#CLIENTKEY AS VARCHAR) + ', ' + CAST(#ADMISSIONKEY AS VARCHAR) + ', ' +
ISNULL(CAST(#PGMKEY AS VARCHAR),'') + ', ' + ISNULL(CAST(#PGMADMISSIONKEY AS VARCHAR),'') + ', ' + CAST(#STAFFKEY AS VARCHAR) + ', ' +
CAST(#GroupSize AS VARCHAR) + ', ' + CAST(#MealTime AS VARCHAR) + ', ' + CAST(#ApprvMgr AS VARCHAR) + ', '
+ CAST(#SessionNum AS VARCHAR) + ', ' + CAST(#FacilityKey AS VARCHAR) + ', ' --Added 10/30/15 JF for FC notes
+ #TtmNoteText +',' --Added 10/30/15 JF for FC notes
+ 'NULL' + ', ' + 'NULL' + ')'
EXEC(#SQLINSERT + #SQLVALUES)
And I want #TtmNoteText to include char(10) and Char(13) like the following
SET #TtmNoteText='Purpose Statement: '+CHAR(13)+CHAR(10) --Added 10/30/15 JF for FC notes
+ 'Family Vision: '+CHAR(13)+CHAR(10)
+ 'Strengths: '+CHAR(13)+CHAR(10)
+ 'Challenges: '+CHAR(13)+CHAR(10)
+ 'Updates: '+CHAR(13)+CHAR(10)
+ 'Progress in Treatment Goals/ITFC Program: '+CHAR(13)+CHAR(10)
+ 'Services/Supports Needed: '+CHAR(13)+CHAR(10)
+ 'Plan:'
I know that I am likely just not using the correct number of single quotes or something like that. Is it possible to insert with line/carriage breaks using dynamic sql
Your entire #SQLVALUES variable is missing a lot of quotes. I'm not sure if this is perfectly accurate, but you need to put single quotes around your string values, but since you're building a dynamic statement, they need to be escaped (escape ' with '):
SET #SQLVALUES = 'VALUES (''' + CAST(#NEWDOCID AS VARCHAR) + ''', ''' + CAST(#CLIENTKEY AS VARCHAR) + ''', ''' +
CAST(#CLIENTKEY AS VARCHAR) + ''', ''' + CAST(#CLIENTKEY AS VARCHAR) + ''', ''' + CAST(#ADMISSIONKEY AS VARCHAR) + ''', ''' +
ISNULL(CAST(#PGMKEY AS VARCHAR),'') + ''', ''' + ISNULL(CAST(#PGMADMISSIONKEY AS VARCHAR),'') + ''', ''' + CAST(#STAFFKEY AS VARCHAR) + ''', ''' +
CAST(#GroupSize AS VARCHAR) + ''', ''' + CAST(#MealTime AS VARCHAR) + ''', ''' + CAST(#ApprvMgr AS VARCHAR) + ''', '''
+ CAST(#SessionNum AS VARCHAR) + ''', ''' + CAST(#FacilityKey AS VARCHAR) + ''', ''' --Added 10/30/15 JF for FC notes
+ #TtmNoteText +''',' --Added 10/30/15 JF for FC notes
+ 'NULL' + ', ' + 'NULL' + ')'
Secondly, I'm not sure you're allowed to use expressions within an EXEC. You might need to do some concatenation before passing to EXEC:
SET #SQLINSERT = #SQLINSERT + #SQLVALUES
EXEC(#SQLINSERT)
Related
I have created a stored procedure that returns a single string of concatenated fields. The issue is that some of these fields may be empty strings resulting in a string much like the below:
, Mendip Road, Farnborough, Hampshire, GU14 9LS
or even
, , Farnborough, Hampshire, GU14 9LS
I really want to strip off any leading commas but I'll only know this once the query has been executed. Is there a way of executing the query, pattern-matching the commas and then removing them before finally returning the modified string?
The query itself is as follows:
SET #SQLQuery = 'SELECT TOP 1 REPLACE((ISNULL(POI,'''') + '', '' + ISNULL(Name,'''') + '', '''
+ ' + ISNULL(Settlement,'''') + '', '' + ISNULL(Cou_Unit,'''') + '', '' + ISNULL(Postcode,'''')),'', , '', '', '')'
+ ' AS ClosestAddress FROM [UKStreetsAndPlaces].[dbo].[OS_Locator] ORDER BY '
+ ' (Longitude ' + #LongitudeOperator + ' ' + CAST(ABS(#Longitude) AS VARCHAR(20)) + ')'
+ ' * (Longitude ' + #LongitudeOperator + ' ' + CAST(ABS(#Longitude) AS VARCHAR(20)) + ')'
+ ' + (Latitude - ' + CAST(#Latitude AS VARCHAR(20)) + ') * (Latitude - ' + CAST(#Latitude AS VARCHAR(20)) + ') ASC'
EXECUTE(#SQLQuery)
Concatenate the comma inside the ISNULL expression as follows:
ISNULL(POI + ', ','')
so your query will look like:
SET #SQLQuery = 'SELECT TOP 1 REPLACE((ISNULL(POI + '', '','''') + ISNULL(Name + '', '','''')'
+ ' + ISNULL(Settlement + '', '','''') + ISNULL(Cou_Unit + '', '','''') + ISNULL(Postcode,'''')),'', , '', '', '')'
+ ' AS ClosestAddress FROM [UKStreetsAndPlaces].[dbo].[OS_Locator] ORDER BY '
+ ' (Longitude ' + #LongitudeOperator + ' ' + CAST(ABS(#Longitude) AS VARCHAR(20)) + ')'
+ ' * (Longitude ' + #LongitudeOperator + ' ' + CAST(ABS(#Longitude) AS VARCHAR(20)) + ')'
+ ' + (Latitude - ' + CAST(#Latitude AS VARCHAR(20)) + ') * (Latitude - ' + CAST(#Latitude AS VARCHAR(20)) + ') ASC'
I don't know if you need dynamic SQL for some other reason, but I think something like this should work (with no Dynamic SQL); if you're really sure you need Dynamic SQL for some other reason, then just refactor this idea into your Dynanmic Statement:
DECLARE #ClosestAddress VARCHAR(1000)
SELECT TOP 1
#ClosestAddress = ISNULL(POI + ', ','')
+ ISNULL(Name + ', ','')
+ ISNULL(Settlement + ', ','')
+ ISNULL(Cou_Unit + ', ', '')
+ ISNULL(Postcode,'')
--AS ClosestAddress
FROM [UKStreetsAndPlaces].[dbo].[OS_Locator] ORDER BY (Longitude = 12.2132) * (Longitude = 12.2132) + (Latitude - 12.2132) * (Latitude - 12.2132) ASC
IF (RIGHT(#ClosestAddress, 2) = ', ')
RETURN SUBSTRING(#ClosestAddress, 0, LEN(#ClosestAddress))
ELSE
RETURN #ClosestAddress
Why this should work: Concatenating NULL + ', ' will result in an empty string. Then we check if the string ends with ', ', and if so we return everything but the last two characters.
You could do something like Replace all Comma with space and then do LTRIM and RTRIM and replace all space with comma.
Create table Data(name varchar(10),lastname varchar(10));
insert into Data values('','Doe');
insert into Data values('Jane','Doe');
insert into Data values('Jane','');
SELECT Replace(Rtrim(Ltrim(Replace(ISNULL(name,'') +',' + ISNULL(lastname,'') + ',',',',' '))),' ',',')
from Data
something like : http://sqlfiddle.com/#!3/6a6c6/1
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))+ '''
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) + ''') ' +
I am using a dynamic stored procedure
if #ReportType = 'Daily Batch'
begin
set #SelectionList= 'select ''' + #tag0 + ''' as Tag0 , ''' + #tag1 + ''' as Tag1 , ''' + #tag2 + ''' as Tag2 , ''' + #tag3 + ''' as Tag3 , ''' + #tag4 + ''' as Tag4 , ''' + #tag5 + ''' as Tag5
, ''' + #tag6 + ''' as Tag6 , ''' + #tag7 + ''' as Tag7 , ''' + #tag8 + ''' as Tag8 , ''' + #tag9 + ''' as Tag9 , ''' + #tag10 + ''' as Tag10 , ''' + #tag11 + ''' as Tag11
, ' + #value0 + ' as Value0 , ' + #value1 + ' as Value1, ' + #value2 + ' as Value2 , ' + #value3 + ' as Value3 , ' + #value4 + ' as Value4 , ' + #value5 + ' as Value5
, ' + #value6 + ' as Value6 , ' + #value7 + ' as Value7 , ' + #value8 + ' as Value8 , ' + #value9 + ' as Value9 , ' + #value10 + ' as Value10 , ' + #value11 + ' as Value11
, RefProductWgt1, RefProductWgt2, RefProductWgt3, RefProductWgt4, RefProductWgt5, RefProductWgt6, RefProductWgt7, RefProductWgt8,
RefProductWgt9, RefProductWgt10, ProductCount, PassCount, RejectCount, UnderWgts, OverWgts, DoubleCount, ReportId, StartDate as GroupColumn
FROM BatchMaster
WHERE SUBSTRING(StartDate, 0, charindex('/' , StartDate, 0))='''+ #startdate+''') AND (DeviceId = '''+#devid+''')
end
exec (#SelectionList)
Here #SelectionList data type is nvarchar(3000), I just want to extract data from a DateTime column...
But it is showing this error:
Operand data type varchar is invalid for divide operator.
Here '/' is used as character not divide, because in my column DateStoreLike (dd-mm-yy/HH:MM:SS), and I am trying to extract only date part before '/' symbol
The error you are receiving is because you need to have two single quotes on each side of the slash:
...WHERE SUBSTRING(StartDate, 0, charindex(''/'' , StartDate, 0))='''+ #startdate+''') AND (DeviceId = '''+#devid+''')
For instance, the following two queries will return '5' as the result:
SELECT charindex('/' , 'this/string', 0)
DECLARE #sql VARCHAR (55) = 'SELECT charindex(''/'' , ''this/string'', 0)'
EXEC(#sql)
When you want a single quote to appear within a string, you need to use two single quotes. To demonstrate this, you can run the following:
SELECT '' --This will return an empty string
SELECT '''' --This will return a single quotation mark
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'