I have a problem that I can not solve, my final goal is to make a trigger that runs every time it is inserted in the 'factura' table and then fill an intermediate table that only has one field (varchar max), because ?, because I have a component in Java that reads this field and generates a file.txt that he later used, but I have a problem that I can not solve, I was seeing what could be with a cursor or better still with a while loop but I am entangled, the BD manager that I use is SQL Server 2008, the select query that I use to generate the data that will be filled in the intermediate table in the trigger, consists of two parts, the header and the details, which I seek to do is that it only shows one row per header, but since there are more than 1 detail in some cases it shows repeated rows.
This is my query:
select
--HEADER(CB),
'CB' + '|' + CONVERT(varchar(10),(CONVERT(DATE, f.FECHA))) + '|' +
'20601140897' + '|' + '03' + '|' +
SUBSTRING(f.SERIE, 1, 2) + '0' + SUBSTRING(f.SERIE, 3, 2) + '-' +
REPLACE(STR(f.NUMERO, 8), SPACE(1), '0') + '|' +
CASE
WHEN f.CODIGO = '' THEN '99999999'
ELSE f.CODIGO
END + '|' + '0' + '|' +
CASE
WHEN f.NOMBRE ='' THEN 'Clientes varios'
ELSE f.NOMBRE
END + '|PEN|' +
CONVERT(varchar(13), (CAST(f.SUBTOTAL AS decimal(10, 2)))) +
'|0.00|0.00|' +
CONVERT(varchar(13), (CAST(f.IMPUESTO AS decimal(10, 2)))) +
'|0.00|0.00|0.00|0.00|' +
CONVERT(varchar(13), (cast(f.TOTAL as decimal(10, 2)))) + '|0.00|0.00|' +
'MONTO TOTAL' + '|||||||1000||||0.00|0.00|0.00||' + CHAR(13) + CHAR(10) +
--DETAIL(DF)
'DB' + '|' + 'NUMBER OF ROW' + '|' + d.PRODUCTO + '|' + 'NIU' + '|' + '1' + '|' +
d.DESCRIPCIO + '|' + CONVERT(varchar(13),(ROUND((d.PRECIO/1.18), 2))) + '|' +
CONVERT(varchar(13), (cast(d.PRECIO as decimal(10, 2)))) + '|' +
CONVERT(varchar(13), (ROUND(((d.PRECIO/1.18) * 0.18), 2))) + '|10|0.00||' +
CONVERT(varchar(13), (cast(d.TOTAL as decimal(10, 2)))) + '|0.00||0.00||'
FROM
factura f
FULL JOIN
detalle d ON f.NUMERO = d.NUMERO
FULL JOIN
clientes c ON f.CODIGO = c.codigo
And this is what it shows:
CB|2017-10-08|20601140897|03|B001-00002224|000700323|0|Clientes
varios|PEN|25.42|0.00|0.00|4.58|0.00|0.00|0.00|0.00|30.00|0.00|0.00|MONTO
TOTAL|||||||1000||||0.00|0.00|0.00|| DB|NUMBER OF
ROW|220|NIU|1|TODO EL
DIA|8.47|10.00|1.53|10|0.00||10.00|0.00||0.00||
CB|2017-10-08|20601140897|03|B001-00002224|000700323|0|Clientes
varios|PEN|25.42|0.00|0.00|4.58|0.00|0.00|0.00|0.00|30.00|0.00|0.00|MONTO
TOTAL|||||||1000||||0.00|0.00|0.00|| DB|NUMBER OF
ROW|230|NIU|1|10 MIN FIN DE
SEMANA|16.94|20.00|3.06|10|0.00||20.00|0.00||0.00||
What I look for:
CB|2017-10-08|20601140897|03|B001-00002224|000700323|0|Clientes
varios|PEN|25.42|0.00|0.00|4.58|0.00|0.00|0.00|0.00|30.00|0.00|0.00|MONTO
TOTAL|||||||1000||||0.00|0.00|0.00|| DB|NUMBER OF
ROW|220|NIU|1|TODO EL
DIA|8.47|10.00|1.53|10|0.00||10.00|0.00||0.00|| DB|NUMBER OF
ROW|230|NIU|1|10 MIN FIN DE
SEMANA|16.94|0.00|3.06|10|0.00||20.00|0.00||0.00||
Somebody could help me? or give me a structure to be able to achieve it, please, I'd be really grateful.
Here is the query, which will append the detail data when there is an identical header data. Query is slow as it involves JOIN on string and large column, You can replace CTE with temp table and by adding index may give a better performance.
;WITH CTE AS (
select
--HEADER(CB),
'CB' + '|' + CONVERT(varchar(10),(CONVERT(DATE, f.FECHA))) + '|' +
'20601140897' + '|' + '03' + '|' +
SUBSTRING(f.SERIE, 1, 2) + '0' + SUBSTRING(f.SERIE, 3, 2) + '-' +
REPLACE(STR(f.NUMERO, 8), SPACE(1), '0') + '|' +
CASE
WHEN f.CODIGO = '' THEN '99999999'
ELSE f.CODIGO
END + '|' + '0' + '|' +
CASE
WHEN f.NOMBRE ='' THEN 'Clientes varios'
ELSE f.NOMBRE
END + '|PEN|' +
CONVERT(varchar(13), (CAST(f.SUBTOTAL AS decimal(10, 2)))) +
'|0.00|0.00|' +
CONVERT(varchar(13), (CAST(f.IMPUESTO AS decimal(10, 2)))) +
'|0.00|0.00|0.00|0.00|' +
CONVERT(varchar(13), (cast(f.TOTAL as decimal(10, 2)))) + '|0.00|0.00|' +
'MONTO TOTAL' + '|||||||1000||||0.00|0.00|0.00||' + CHAR(13) + CHAR(10) HeaderData,
--DETAIL(DF)
'DB' + '|' + 'NUMBER OF ROW' + '|' + d.PRODUCTO + '|' + 'NIU' + '|' + '1' + '|' +
d.DESCRIPCIO + '|' + CONVERT(varchar(13),(ROUND((d.PRECIO/1.18), 2))) + '|' +
CONVERT(varchar(13), (cast(d.PRECIO as decimal(10, 2)))) + '|' +
CONVERT(varchar(13), (ROUND(((d.PRECIO/1.18) * 0.18), 2))) + '|10|0.00||' +
CONVERT(varchar(13), (cast(d.TOTAL as decimal(10, 2)))) + '|0.00||0.00||' DetailData
FROM factura f FULL JOIN detalle d ON f.NUMERO = d.NUMERO
FULL JOIN clientes c ON f.CODIGO = c.codigo
)
select HeaderData+STUFF((SELECT '|'+ DetailData
FROM CTE C
WHERE C.HeaderData=T.HeaderData
FOR XML PATH('')),1,1,'')
FROM CTE T
GROUP BY HeaderData
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
Why does my sorting not work as it should? If i click to sort the value of my select under then it only sorts after the first number so if i have values like 100,33,2100,4432 then i get this order 100,2100,33,4432
How can 100 be smaller then 33 and so on...
SELECT Replace(
CONVERT(VARCHAR,
CONVERT(INTEGER, Sum(
Isnull(
a.planabsatz_mt1 + a.planabsatz_mt2
+ a.planabsatz_mt3 + a.planabsatz_mt4
+ a.planabsatz_mt5 + a.planabsatz_mt6
+ a.planabsatz_mt7 + a.planabsatz_mt8
+ a.planabsatz_mt9 + a.planabsatz_mt10
+ a.planabsatz_mt11 + a.planabsatz_mt12, 0))), 1),
'.00', '')
You've converted your values to strings in the select statement you posted.
So, doing an alpha sort, 100 does come before 33.
You're converting the number to a varchar before sorting. Try this:
SELECT Replace(
CONVERT(INTEGER, Sum(
Isnull(
a.planabsatz_mt1 + a.planabsatz_mt2
+ a.planabsatz_mt3 + a.planabsatz_mt4
+ a.planabsatz_mt5 + a.planabsatz_mt6
+ a.planabsatz_mt7 + a.planabsatz_mt8
+ a.planabsatz_mt9 + a.planabsatz_mt10
+ a.planabsatz_mt11 + a.planabsatz_mt12, 0))),
'.00', '')
I use the following as an export query and I had to transfer to a new upgraded windows server 2003-2008R2. I also upgraded from SQL 2005 to SQL 2012 and apparently screwed up some permission. The following code is supposed to write to a file that gets picked up by dbmail and emailed. The problem is its not writing the file and I believe permissions to be the problem but am not sure where I went wrong. I known th this works as it worked for years on the other server without a hitch so the problem has to be permissions I am guessing.
The message I get is as follows and occurs because the file is never created:
Executed as user: NT SERVICE\SQLSERVERAGENT. Attachment file D:\Argosy_import_090513_0001.txt is invalid. [SQLSTATE 42000] (Error 22051). The step failed.
Declare #PeriodStart Datetime
Declare #PeriodEnd Datetime
SELECT #PeriodEnd = GetDate()
,#PeriodStart = dateadd(hour,-72,getdate())
;WITH outpQ
AS
(
SELECT 1 AS grpOrd, CAST(null AS VARCHAR(255)) AS posInGrp, 'A' AS Ord, CaseNumberKey, 'A|' + ClientsKey + '|' + CAST(BRTNumber AS VARCHAR(11)) + '|' + IsNull(replace(convert(char(10), CoverDate, 101), '/', ''), '') + '|' + IsNull(replace(convert(char(10), CoverDate, 101), '/', ''), '') + '|' + IsNull(ParcelNumber, '') + '|' + IsNull(AssessedBeg, '') + '|' + IsNull(AssessedDim, '') + '|' + IsNull(AbbrLegal, '') + '|' + IsNull(WaterFrom, '') + '|' + IsNull(WaterTo, '') + '|' + IsNull(Cast(WaterOpen AS VARCHAR(50)), '') + '|' + IsNull(TaxFrom, '') + '|' + IsNull(TaxTo, '') + '|' + IsNull(Cast(TaxOpen AS VARCHAR(50)), '') AS Extract
FROM newCityCollection.dbo.PropertyInformation
WHERE DateFinished BETWEEN #PeriodStart AND #PeriodEnd AND ClientKey = 2
UNION ALL
SELECT 1 As grpOrd, null AS posInGrp, 'A1', A.CaseNumberKey, 'A1|' + '|' + '|' + B.LienNumber + '|' + IsNull(Cast(B.LienAmt AS VARCHAR(50)), '') + '|' + IsNull(replace(LienDate, '/', ''), '') + '|' + IsNull(B.LienReason, '') AS Extract
FROM newCityCollection.dbo.PropertyInformation A
JOIN newCityCollection.dbo.muniLiens B ON B.CaseNumberKey = A.CaseNumberKey
WHERE A.DateFinished BETWEEN #PeriodStart AND #PeriodEnd AND ClientKey = 2
UNION ALL
SELECT 2 AS grpOrd, CAST(C.InterestsKey AS VARCHAR(11)) AS posInGrp, 'B', A.CaseNumberKey, 'B|' + '|' + IsNull(C.First, '') + '|' + IsNull(C.Middle, '') + '|' + IsNull(C.Last, '') + '|' + IsNull(C.Alias, '') + '|' + IsNull(C.ComName, '') + '|' + IsNull(C.DocRel, '') + '|' + Cast(C.InterestsKey AS VARCHAR(11)) AS Extract
FROM newCityCollection.dbo.PropertyInformation A
JOIN newCityCollection.dbo.Interests C ON C.CaseNumberKey = A.CaseNumberKey
WHERE A.DateFinished BETWEEN #PeriodStart AND #PeriodEnd AND ClientKey = 2
UNION ALL
SELECT 2 AS grpOrd, CAST(C.InterestsKey AS VARCHAR(11)) AS posInGrp, 'B1', A.CaseNumberKey, 'B1|' + IsNull(FullAdd, '') + '|' + IsNull(D.City, '') + '|' + IsNull(D.State, '') + '|' + IsNull(D.Zip, '') AS Extract
FROM newCityCollection.dbo.PropertyInformation A
JOIN newCityCollection.dbo.Interests C ON C.CaseNumberKey = A.CaseNumberKey
JOIN newCityCollection.dbo.InterestAdd D ON D.CaseNumberKey = A.CaseNumberKey AND D.InterestsKey = C.InterestsKey
WHERE A.DateFinished BETWEEN #PeriodStart AND #PeriodEnd AND ClientKey = 2
UNION ALL
SELECT 2 AS grpOrd, CAST(C.InterestsKey AS VARCHAR(11)) AS posInGrp, 'B2', A.CaseNumberKey, 'B2|' + '|' + IsNull(E.SuitNumber, '') + '|' + Cast(E.BDate AS VARCHAR(11)) + '|' + IsNull(E.Chapter, '') + '|' + IsNull(E.VS, '') AS Extract
FROM newCityCollection.dbo.PropertyInformation A
JOIN newCityCollection.dbo.Interests C ON C.CaseNumberKey = A.CaseNumberKey
JOIN newCityCollection.dbo.Banks E ON E.CaseNumberKey = A.CaseNumberKey AND E.InterestsKey = C.InterestsKey
WHERE A.DateFinished BETWEEN #PeriodStart AND #PeriodEnd AND ClientKey = 2
UNION ALL
SELECT 3 As grpOrd3, null AS posInGrp, 'B3', A.CaseNumberKey, 'B3|' + '|' + F.DocType + '|' + IsNull(Cast(F.DocAmt AS VARCHAR(50)), '') + '|' + IsNull(replace(convert(char(10), DocDate, 101), '/', ''), '') + '|' + IsNull(replace(convert(char(10), RecDate, 101), '/', ''), '') + '|' + IsNull(F.DocID, '') + '|' + IsNull(F.Grantee,'') + '|' + IsNull(F.Grantor,'') + Cast(F.DocIDKey AS VARCHAR(11)) AS Extract
FROM newCityCollection.dbo.PropertyInformation A
JOIN newCityCollection.dbo.Documents F ON F.CaseNumberKey = A.CaseNumberKey
WHERE A.DateFinished BETWEEN #PeriodStart AND #PeriodEnd AND ClientKey = 2
UNION ALL
SELECT 4 AS grpOrd, null AS posInGrp, 'C', A.CaseNumberKey, 'C|' + IsNull(J.CType, '') + '|' + IsNull(J.plaintiffName,'') + '|' + IsNull(J.plaintiffAdd1, '') + '|' + IsNull(J.plaintiffCity, '') + '|' + IsNull(J.plaintiffState, '') + '|' + IsNull(J.plaintiffZip, '') + '|' + '|' + IsNull(J.defendantName, '') + '|' + IsNull(J.defendantAdd1, '') + '|' + IsNull(J.defCity, '') + '|' + IsNull(J.defState, '') + '|' + IsNull(J.defZip, '') + '|' + '|' + IsNull(J.Court, '') + '|' + IsNull(J.CaseID, '') + '|' + IsNull(J.JAmt, '') + '|' + IsNull(replace(convert(VarChar(10), JDate, 101), '/', ''), '') + '|' + IsNull(replace(convert(VARCHAR(10), revivedDate, 101), '/', ''), '') AS Extract
FROM newCityCollection.dbo.PropertyInformation A
JOIN Acme.new_judgment_system.dbo.selected_compiled_clean J ON J.CaseNumber = A.CaseNumberKey
WHERE A.DateFinished BETWEEN #PeriodStart AND #PeriodEnd AND ClientKey = 2 AND J.plaintiffName NOT IN (SELECT Plaintiff FROM newCityCollection.dbo.excluded_Plaintiffs)
)
--Extract data set into a table -- dump table in .txt with current date as part of name then delete that table
SELECT Extract INTO datadump FROM outpQ ORDER BY CaseNumberKey, grpOrd, posInGrp, Ord
DECLARE #FileName varchar(50),
#bcpCommand varchar(2000)
SET #FileName = REPLACE('D:\Argosy_import_'+CONVERT(char(8),GETDATE(),1)+'_0001.txt','/','')
SET #bcpCommand = 'bcp "SELECT Extract FROM datadump" QUERYOUT "'
SET #bcpCommand = #bcpCommand + #FileName + '" -U sa -P ********** -T -c'
EXEC master..xp_cmdshell #bcpCommand
DROP table datadump
EXEC msdb.dbo.sp_send_dbmail
#recipients=N'giner#gmail.com',
#body='Message Body',
#subject ='Import file from My Company',
#profile_name ='Mail',
#file_attachments = #FileName;
Did the attachment size get changed to the default?
See if the attachment exists on the server!
Code below shows current attachment size and then sets max size for DBMail.
-- show current size
exec msdb.dbo.sysmail_help_configure_sp 'MaxFileSize'
-- set the max attachment size to 20000 bytes
exec msdb.dbo.sysmail_configure_sp 'MaxFileSize', '20000';
Also, make sure that the attachment extension is allowed in mail.
-- show prohibited extensions
EXEC msdb.dbo.sysmail_help_configure_sp 'ProhibitedExtensions'
Observed a strange behavior with BCP command:
i. If BCP command is executed from command shell, then the file generated is on the local machine
ii. Else if BCP command is executed on SQL Server Management Studio, the file generated is on the server name mentioned with the command.
Hence, make sure you are providing the proper server name (-S parameter) in BCP command.
I have a table where all the fields are declared as nvarchar. If I do an insert into the table all unicode characters come into the fields fine. But when I do an update I am losing some of the characters. Here is my udpate statement:
UPDATE TableII
SET LOCATION = CAST(( COALESCE([CITY], N'') + NCHAR(13) + NCHAR(10)
+ COALESCE([INSTALLATION], N'') + NCHAR(13)
+ NCHAR(10) + LEFT(LOCATION.LATLONG, 2) + N'°'
+ SUBSTRING(LOCATION.LATLONG, 3, 2) + N''''
+ SUBSTRING(LOCATION.LATLONG, 5, 2) + NCHAR(34)
+ N' ' + SUBSTRING(LOCATION.LATLONG, 7, 1)
+ N' ' + SUBSTRING(LOCATION.LATLONG, 8, 3)
+ N'°' + SUBSTRING(LOCATION.LATLONG, 11, 2)
+ N'''' + SUBSTRING(LOCATION.LATLONG, 13, 2)
+ NCHAR(34) + N' ' + SUBSTRING(LOCATION.LATLONG,
15, 1) ) AS NVARCHAR(MAX))
FROM TABLEII
INNER JOIN LOC ON TABLEII.REC = LOC.REC
INNER JOIN LOCATION ON LOC.LOCRECNUM = LOCATION.LOCRECNUM
WHERE ( LOC.LOCSEQ = '1' )
As you can see I have tried a variety of things to force the unicode characters to not be lost, but it does not work.
Any ideas why the insert works fine but this update does not?
Is the City column NVARCHAR? If not, the COALESCE will take that column as it's data type and use it, regardless of what you do with the rest of the code.
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'