Search Results

Search found 355 results on 15 pages for 'getdate'.

Page 2/15 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Sorting and Re-arranging List of HashMaps

    - by HonorGod
    I have a List which is straight forward representation of a database table. I am trying to sort and apply some magic after the data is loaded into List of HashMaps. In my case this is the only hard and fast way of doing it becoz I have a rules engine that actually updates the values in the HashMap after several computations. Here is a sample data representation of the HashMap (List of HashMap) - {fromDate=Wed Mar 17 10:54:12 EDT 2010, eventId=21, toDate=Tue Mar 23 10:54:12 EDT 2010, actionId=1234} {fromDate=Wed Mar 17 10:54:12 EDT 2010, eventId=11, toDate=Wed Mar 17 10:54:12 EDT 2010, actionId=456} {fromDate=Sat Mar 20 10:54:12 EDT 2010, eventId=20, toDate=Thu Apr 01 10:54:12 EDT 2010, actionId=1234} {fromDate=Wed Mar 24 10:54:12 EDT 2010, eventId=22, toDate=Sat Mar 27 10:54:12 EDT 2010, actionId=1234} {fromDate=Wed Mar 17 10:54:12 EDT 2010, eventId=11, toDate=Fri Mar 26 10:54:12 EDT 2010, actionId=1234} {fromDate=Sat Mar 20 10:54:12 EDT 2010, eventId=11, toDate=Wed Mar 31 10:54:12 EDT 2010, actionId=1234} {fromDate=Mon Mar 15 10:54:12 EDT 2010, eventId=12, toDate=Wed Mar 17 10:54:12 EDT 2010, actionId=567} I am trying to achieve couple of things - 1) Sort the list by actionId and eventId after which the data would look like - {fromDate=Wed Mar 17 10:54:12 EDT 2010, eventId=11, toDate=Wed Mar 17 10:54:12 EDT 2010, actionId=456} {fromDate=Mon Mar 15 10:54:12 EDT 2010, eventId=12, toDate=Wed Mar 17 10:54:12 EDT 2010, actionId=567} {fromDate=Wed Mar 24 10:54:12 EDT 2010, eventId=22, toDate=Sat Mar 27 10:54:12 EDT 2010, actionId=1234} {fromDate=Wed Mar 17 10:54:12 EDT 2010, eventId=21, toDate=Tue Mar 23 10:54:12 EDT 2010, actionId=1234} {fromDate=Sat Mar 20 10:54:12 EDT 2010, eventId=20, toDate=Thu Apr 01 10:54:12 EDT 2010, actionId=1234} {fromDate=Wed Mar 17 10:54:12 EDT 2010, eventId=11, toDate=Fri Mar 26 10:54:12 EDT 2010, actionId=1234} {fromDate=Sat Mar 20 10:54:12 EDT 2010, eventId=11, toDate=Wed Mar 31 10:54:12 EDT 2010, actionId=1234} 2) If we group the above list by actionId they would be resolved into 3 groups - actionId=1234, actionId=567 and actionId=456. Now here is my question - For each group having the same eventId, I need to update the records so that they have wider fromDate to toDate. Meaning, if you consider the last two rows they have same actionId = 1234 and same eventId = 11. Now we can to pick the least fromDate from those 2 records which is Wed Mar 17 10:54:12 and farther toDate which is Wed Mar 31 10:54:12 and update those 2 record's fromDate and toDate to Wed Mar 17 10:54:12 and Wed Mar 31 10:54:12 respectively. Any ideas? PS: I already have some pseudo code to start with. import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import org.apache.commons.lang.builder.CompareToBuilder; public class Tester { boolean ascending = true ; boolean sortInstrumentIdAsc = true ; boolean sortEventTypeIdAsc = true ; public static void main(String args[]) { Tester tester = new Tester() ; tester.printValues() ; } public void printValues () { List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>() ; HashMap<String,Object> map = new HashMap<String,Object>(); map.put("actionId", new Integer(1234)) ; map.put("eventId", new Integer(21)) ; map.put("fromDate", getDate(1) ) ; map.put("toDate", getDate(7) ) ; list.add(map); map = new HashMap<String,Object>(); map.put("actionId", new Integer(456)) ; map.put("eventId", new Integer(11)) ; map.put("fromDate", getDate(1)) ; map.put("toDate", getDate(1) ) ; list.add(map); map = new HashMap<String,Object>(); map.put("actionId", new Integer(1234)) ; map.put("eventId", new Integer(20)) ; map.put("fromDate", getDate(4) ) ; map.put("toDate", getDate(16) ) ; list.add(map); map = new HashMap<String,Object>(); map.put("actionId", new Integer(1234)) ; map.put("eventId", new Integer(22)) ; map.put("fromDate",getDate(8) ) ; map.put("toDate", getDate(11)) ; list.add(map); map = new HashMap<String,Object>(); map.put("actionId", new Integer(1234)) ; map.put("eventId", new Integer(11)) ; map.put("fromDate",getDate(1) ) ; map.put("toDate", getDate(10) ) ; list.add(map); map = new HashMap<String,Object>(); map.put("actionId", new Integer(1234)) ; map.put("eventId", new Integer(11)) ; map.put("fromDate",getDate(4) ) ; map.put("toDate", getDate(15) ) ; list.add(map); map = new HashMap<String,Object>(); map.put("actionId", new Integer(567)) ; map.put("eventId", new Integer(12)) ; map.put("fromDate", getDate(-1) ) ; map.put("toDate",getDate(1)) ; list.add(map); System.out.println("\n Before Sorting \n "); for(int j = 0 ; j < list.size() ; j ++ ) System.out.println(list.get(j)); Collections.sort ( list , new HashMapComparator2 () ) ; System.out.println("\n After Sorting \n "); for(int j = 0 ; j < list.size() ; j ++ ) System.out.println(list.get(j)); } public static Date getDate(int days) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DATE, days); return cal.getTime() ; } public class HashMapComparator2 implements Comparator { public int compare ( Object object1 , Object object2 ) { if ( ascending == true ) { return new CompareToBuilder() .append(( ( HashMap ) object1 ).get ( "actionId" ), ( ( HashMap ) object2 ).get ( "actionId" )) .append(( ( HashMap ) object2 ).get ( "eventId" ), ( ( HashMap ) object1 ).get ( "eventId" )) .toComparison(); } else { return new CompareToBuilder() .append(( ( HashMap ) object2 ).get ( "actionId" ), ( ( HashMap ) object1 ).get ( "actionId" )) .append(( ( HashMap ) object2 ).get ( "eventId" ), ( ( HashMap ) object1 ).get ( "eventId" )) .toComparison(); } } } }

    Read the article

  • Script to UPDATE STATISTICS with time window

    - by Bill Graziano
    I recently spent some time troubleshooting odd query plans and came to the conclusion that we needed better statistics.  We’ve been running sp_updatestats but apparently it wasn’t sampling enough of the table to get us what we needed.  I have a pretty limited window at night where I can hammer the disks while this runs.  The script below just calls UPDATE STATITICS on all tables that “need” updating.  It defines need as any table whose statistics are older than the number of days you specify (30 by default).  It also has a throttle so it breaks out of the loop after a set amount of time (60 minutes).  That means it won’t start processing a new table after this time but it might take longer than this to finish what it’s doing.  It always processes the oldest statistics first so it will eventually get to all of them.  It defaults to sample 25% of the table.  I’m not sure that’s a good default but it works for now.  I’ve tested this in SQL Server 2005 and SQL Server 2008.  I liked the way Michelle parameterized her re-index script and I took the same approach. CREATE PROCEDURE dbo.UpdateStatistics ( @timeLimit smallint = 60 ,@debug bit = 0 ,@executeSQL bit = 1 ,@samplePercent tinyint = 25 ,@printSQL bit = 1 ,@minDays tinyint = 30 )AS/******************************************************************* Copyright Bill Graziano 2010*******************************************************************/SET NOCOUNT ON;PRINT '[ ' + CAST(GETDATE() AS VARCHAR(100)) + ' ] ' + 'Launching...'IF OBJECT_ID('tempdb..#status') IS NOT NULL DROP TABLE #status;CREATE TABLE #status( databaseID INT , databaseName NVARCHAR(128) , objectID INT , page_count INT , schemaName NVARCHAR(128) Null , objectName NVARCHAR(128) Null , lastUpdateDate DATETIME , scanDate DATETIME CONSTRAINT PK_status_tmp PRIMARY KEY CLUSTERED(databaseID, objectID));DECLARE @SQL NVARCHAR(MAX);DECLARE @dbName nvarchar(128);DECLARE @databaseID INT;DECLARE @objectID INT;DECLARE @schemaName NVARCHAR(128);DECLARE @objectName NVARCHAR(128);DECLARE @lastUpdateDate DATETIME;DECLARE @startTime DATETIME;SELECT @startTime = GETDATE();DECLARE cDB CURSORREAD_ONLYFOR select [name] from master.sys.databases where database_id > 4OPEN cDBFETCH NEXT FROM cDB INTO @dbNameWHILE (@@fetch_status <> -1)BEGIN IF (@@fetch_status <> -2) BEGIN SELECT @SQL = ' use ' + QUOTENAME(@dbName) + ' select DB_ID() as databaseID , DB_NAME() as databaseName ,t.object_id ,sum(used_page_count) as page_count ,s.[name] as schemaName ,t.[name] AS objectName , COALESCE(d.stats_date, ''1900-01-01'') , GETDATE() as scanDate from sys.dm_db_partition_stats ps join sys.tables t on t.object_id = ps.object_id join sys.schemas s on s.schema_id = t.schema_id join ( SELECT object_id, MIN(stats_date) as stats_date FROM ( select object_id, stats_date(object_id, stats_id) as stats_date from sys.stats) as d GROUP BY object_id ) as d ON d.object_id = t.object_id where ps.row_count > 0 group by s.[name], t.[name], t.object_id, COALESCE(d.stats_date, ''1900-01-01'') ' SET ANSI_WARNINGS OFF; Insert #status EXEC ( @SQL); SET ANSI_WARNINGS ON; END FETCH NEXT FROM cDB INTO @dbNameENDCLOSE cDBDEALLOCATE cDBDECLARE cStats CURSORREAD_ONLYFOR SELECT databaseID , databaseName , objectID , schemaName , objectName , lastUpdateDate FROM #status WHERE DATEDIFF(dd, lastUpdateDate, GETDATE()) >= @minDays ORDER BY lastUpdateDate ASC, page_count desc, [objectName] ASC OPEN cStatsFETCH NEXT FROM cStats INTO @databaseID, @dbName, @objectID, @schemaName, @objectName, @lastUpdateDateWHILE (@@fetch_status <> -1)BEGIN IF (@@fetch_status <> -2) BEGIN IF DATEDIFF(mi, @startTime, GETDATE()) > @timeLimit BEGIN PRINT '[ ' + CAST(GETDATE() AS VARCHAR(100)) + ' ] ' + '*** Time Limit Reached ***'; GOTO __DONE; END SELECT @SQL = 'UPDATE STATISTICS ' + QUOTENAME(@dBName) + '.' + QUOTENAME(@schemaName) + '.' + QUOTENAME(@ObjectName) + ' WITH SAMPLE ' + CAST(@samplePercent AS NVARCHAR(100)) + ' PERCENT;'; IF @printSQL = 1 PRINT '[ ' + CAST(GETDATE() AS VARCHAR(100)) + ' ] ' + @SQL + ' (Last Updated: ' + CAST(@lastUpdateDate AS VARCHAR(100)) + ')' IF @executeSQL = 1 BEGIN EXEC (@SQL); END END FETCH NEXT FROM cStats INTO @databaseID, @dbName, @objectID, @schemaName, @objectName, @lastUpdateDateEND__DONE:CLOSE cStatsDEALLOCATE cStatsPRINT '[ ' + CAST(GETDATE() AS VARCHAR(100)) + ' ] ' + 'Completed.'GO

    Read the article

  • stored procedure issue, has to do with my where clause and if statement

    - by MyHeadHurts
    right now my stored procedure is returning 2 different result sets one for @booked and the other for @booked1 if you look closely my query is doing the same thing for each @booked and @booked but one is for a user selected year and the other for the current year. I don't want two different result sets, i want to join the selected year and the current year side by side by SDESCR(which is a column that they have in common) another hurdle i am facing is i am use @mode to decide whether the user wants netsales, sales... so on. I know i need sometype of join but, it isnt working because i have a where statement that says where dyyyy= @yeartoget which won't allow the current year data to work ALTER PROCEDURE [dbo].[test1] @mode varchar(20), @YearToGet int AS SET NOCOUNT ON Declare @Booked Int Set @Booked = CONVERT(int,DateAdd(year, @YearToGet - Year(getdate() + 1), DateAdd(day, DateDiff(day, 1, getdate()), 1) ) ) Declare @Booked1 Int Set @Booked1 = CONVERT(int,DateAdd(year, (year( getdate() )) - Year(getdate() + 1), DateAdd(day, DateDiff(day, 1, getdate()), 1) ) ) If @mode = 'Sales' Select Division, SDESCR, DYYYY, Sum(Case When Booked <= @Booked Then NetAmount End) ASofNetSales, SUM(NetAmount) AS YENetSales, Sum(Case When Booked <= @Booked Then PARTY End) AS ASofPAX, SUM(PARTY) AS YEPAX From dbo.B101BookingsDetails Where DYYYY = @YearToGet Group By SDESCR, DYYYY, Division Order By Division, SDESCR, DYYYY else if @mode = 'netsales' Select Division, SDESCR, DYYYY, Sum(Case When Booked <= @Booked Then NetAmount End) ASofNetSales, SUM(NetAmount) AS YENetSales, Sum(Case When Booked <= @Booked Then PARTY End) AS ASofPAX, SUM(PARTY) AS YEPAX From dbo.B101BookingsDetails Where DYYYY = @YearToGet Group By SDESCR, DYYYY, Division Order By Division, SDESCR, DYYYY If @mode = 'Sales' Select Division, SDESCR, DYYYY, Sum(Case When Booked <= @Booked1 Then NetAmount End) currentNetSales, Sum(Case When Booked <= @Booked1 Then PARTY End) AS currentPAX From dbo.B101BookingsDetails Where DYYYY = (year( getdate() )) Group By SDESCR, DYYYY, Division Order By Division, SDESCR, DYYYY else if @mode = 'netsales' Select Division, SDESCR, DYYYY, Sum(Case When Booked <= @Booked1 Then NetAmount End) currentNetSales, Sum(Case When Booked <= @Booked1 Then PARTY End) AS currentPAX From dbo.B101BookingsDetails Where DYYYY = (year( getdate() )) Group By SDESCR, DYYYY, Division Order By Division, SDESCR, DYYYY Else if @mode = 'Inssales' Select Division, SDESCR, DYYYY, Sum(Case When Booked <= @Booked1 Then InsAmount End) currentInsSales, Sum(Case When Booked <= @Booked1 Then PARTY End) AS currentPAX From dbo.B101BookingsDetails Where DYYYY = (year( getdate() )) Group By SDESCR, DYYYY, Division Order By Division, SDESCR, DYYYY

    Read the article

  • SQL SERVER – Information Related to DATETIME and DATETIME2

    - by pinaldave
    I recently received interesting comment on the blog regarding workaround to overcome the precision issue while dealing with DATETIME and DATETIME2. I have written over this subject earlier over here. SQL SERVER – Difference Between GETDATE and SYSDATETIME SQL SERVER – Difference Between DATETIME and DATETIME2 – WITH GETDATE SQL SERVER – Difference Between DATETIME and DATETIME2 SQL Expert Jing Sheng Zhong has left following comment: The issue you found in SQL server new datetime type is related time source function precision. Folks have found the root reason of the problem – when data time values are converted (implicit or explicit) between different data type, which would lose some precision, so the result cannot match each other as thought. Here I would like to gave a work around solution to solve the problem which the developers met. -- Declare and loop DECLARE @Intveral INT, @CurDate DATETIMEOFFSET; CREATE TABLE #TimeTable (FirstDate DATETIME, LastDate DATETIME2, GlobalDate DATETIMEOFFSET) SET @Intveral = 10000 WHILE (@Intveral > 0) BEGIN ----SET @CurDate = SYSDATETIMEOFFSET(); -- higher precision for future use only SET @CurDate = TODATETIMEOFFSET(GETDATE(),DATEDIFF(N,GETUTCDATE(),GETDATE())); -- lower precision to match exited date process INSERT #TimeTable (FirstDate, LastDate, GlobalDate) VALUES (@CurDate, @CurDate, @CurDate) SET @Intveral = @Intveral - 1 END GO -- Distinct Values SELECT COUNT(DISTINCT FirstDate) D_DATETIME, COUNT(DISTINCT LastDate) D_DATETIME2, COUNT(DISTINCT GlobalDate) D_SYSGETDATE FROM #TimeTable GO -- Join SELECT DISTINCT a.FirstDate,b.LastDate, b.GlobalDate, CAST(b.GlobalDate AS DATETIME) GlobalDateASDateTime FROM #TimeTable a INNER JOIN #TimeTable b ON a.FirstDate = CAST(b.GlobalDate AS DATETIME) GO -- Select SELECT * FROM #TimeTable GO -- Clean up DROP TABLE #TimeTable GO If you read my blog SQL SERVER – Difference Between DATETIME and DATETIME2 you will notice that I have achieved the same using GETDATE(). Are you using DATETIME2 in your production environment? If yes, I am interested to know the use case. Reference: Pinal Dave (http://www.SQLAuthority.com) Filed under: Pinal Dave, SQL, SQL Authority, SQL DateTime, SQL Query, SQL Scripts, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • SQL SERVER – Script to Find First Day of Current Month

    - by Pinal Dave
    Earlier I wrote a blog post about SQL SERVER – Query to Find First and Last Day of Current Month and it is a very popular post. In this post, I convert the datetime to Varchar and later on use it. However, SQL Expert Michael Usov has made a good point suggesting that it is not always a good idea to convert datetime to any other date format as it is quite possible that we may need it the value in the datetime format for other operation. He has suggested a very quick solution where we can get the first day of the current month with or without time value and keep them with datatype datetime. Here is the simple script for the same. -- first day of month -- with time zeroed out SELECT CAST(DATEADD(DAY,-DAY(GETDATE())+1, CAST(GETDATE() AS DATE)) AS DATETIME) -- with time as it was SELECT DATEADD(DAY,-DAY(GETDATE())+1, CAST(GETDATE() AS DATETIME)) Here is the resultset: Reference: Pinal Dave (http://blog.SQLAuthority.com)Filed under: PostADay, SQL, SQL Authority, SQL DateTime, SQL Function, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

    Read the article

  • Linq to SQL with INSTEAD OF Trigger and an Identity Column

    - by Bob Horn
    I need to use the clock on my SQL Server to write a time to one of my tables, so I thought I'd just use GETDATE(). The problem is that I'm getting an error because of my INSTEAD OF trigger. Is there a way to set one column to GETDATE() when another column is an identity column? This is the Linq-to-SQL: internal void LogProcessPoint(WorkflowCreated workflowCreated, int processCode) { ProcessLoggingRecord processLoggingRecord = new ProcessLoggingRecord() { ProcessCode = processCode, SubId = workflowCreated.SubId, EventTime = DateTime.Now // I don't care what this is. SQL Server will use GETDATE() instead. }; this.Database.Add<ProcessLoggingRecord>(processLoggingRecord); } This is the table. EventTime is what I want to have as GETDATE(). I don't want the column to be null. And here is the trigger: ALTER TRIGGER [Master].[ProcessLoggingEventTimeTrigger] ON [Master].[ProcessLogging] INSTEAD OF INSERT AS BEGIN SET NOCOUNT ON; SET IDENTITY_INSERT [Master].[ProcessLogging] ON; INSERT INTO ProcessLogging (ProcessLoggingId, ProcessCode, SubId, EventTime, LastModifiedUser) SELECT ProcessLoggingId, ProcessCode, SubId, GETDATE(), LastModifiedUser FROM inserted SET IDENTITY_INSERT [Master].[ProcessLogging] OFF; END Without getting into all of the variations I've tried, this last attempt produces this error: InvalidOperationException Member AutoSync failure. For members to be AutoSynced after insert, the type must either have an auto-generated identity, or a key that is not modified by the database after insert. I could remove EventTime from my entity, but I don't want to do that. If it was gone though, then it would be NULL during the INSERT and GETDATE() would be used. Is there a way that I can simply use GETDATE() on the EventTime column for INSERTs? Note: I do not want to use C#'s DateTime.Now for two reasons: 1. One of these inserts is generated by SQL Server itself (from another stored procedure) 2. Times can be different on different machines, and I'd like to know exactly how fast my processes are happening.

    Read the article

  • Update table without using cursor and on date

    - by Muhammad Kashif Nadeem
    Please copy and run following script DECLARE @Customers TABLE (CustomerId INT) DECLARE @Orders TABLE ( OrderId INT, CustomerId INT, OrderDate DATETIME ) DECLARE @Calls TABLE (CallId INT, CallTime DATETIME, CallToId INT, OrderId INT) ----------------------------------------------------------------- INSERT INTO @Customers SELECT 1 INSERT INTO @Customers SELECT 2 ----------------------------------------------------------------- INSERT INTO @Orders SELECT 10, 1, DATEADD(d, -20, GETDATE()) INSERT INTO @Orders SELECT 11, 1, DATEADD(d, -10, GETDATE()) ----------------------------------------------------------------- INSERT INTO @Calls SELECT 101, DATEADD(d, -19, GETDATE()), 1, NULL INSERT INTO @Calls SELECT 102, DATEADD(d, -17, GETDATE()), 1, NULL INSERT INTO @Calls SELECT 103, DATEADD(d, -9, GETDATE()), 1, NULL INSERT INTO @Calls SELECT 104, DATEADD(d, -6, GETDATE()), 1, NULL INSERT INTO @Calls SELECT 105, DATEADD(d, -5, GETDATE()), 1, NULL ----------------------------------------------------------------- I want to update @Calls table and need following results. I am using the following query UPDATE @Calls SET OrderId = ( CASE WHEN (s.CallTime > e.OrderDate) THEN e.OrderId END ) FROM @Calls s INNER JOIN @Orders e ON s.CallToId = e.CustomerId and the result of my query is not what I need. Requirement: As you can see there are two orders. One is on 2010-12-12 and one is on 2010-12-22. I want to update @Calls table with relevant OrderId with respect to CallTime. In short If subsequent Orders are added, and there are further calls then we assume that a new call is associated with the most recent Order Note: This is sample data so this is not the case that I always have two Orders. There might be 10+ Orders and 100+ calls. Note2 I could not find good title for this question. Please change it if you think of any better. Thanks.

    Read the article

  • Sub Query making Query slow.

    - by Muhammad Kashif Nadeem
    Please copy and paste following script. DECLARE @MainTable TABLE(MainTablePkId int) INSERT INTO @MainTable SELECT 1 INSERT INTO @MainTable SELECT 2 DECLARE @SomeTable TABLE(SomeIdPk int, MainTablePkId int, ViewedTime1 datetime) INSERT INTO @SomeTable SELECT 1, 1, DATEADD(dd, -10, getdate()) INSERT INTO @SomeTable SELECT 2, 1, DATEADD(dd, -9, getdate()) INSERT INTO @SomeTable SELECT 3, 2, DATEADD(dd, -6, getdate()) DECLARE @SomeTableDetail TABLE(DetailIdPk int, SomeIdPk int, Viewed INT, ViewedTimeDetail datetime) INSERT INTO @SomeTableDetail SELECT 1, 1, 1, DATEADD(dd, -7, getdate()) INSERT INTO @SomeTableDetail SELECT 2, 2, NULL, DATEADD(dd, -6, getdate()) INSERT INTO @SomeTableDetail SELECT 3, 2, 2, DATEADD(dd, -8, getdate()) INSERT INTO @SomeTableDetail SELECT 4, 3, 1, DATEADD(dd, -6, getdate()) SELECT m.MainTablePkId, (SELECT COUNT(Viewed) FROM @SomeTableDetail), (SELECT TOP 1 s2.ViewedTimeDetail FROM @SomeTableDetail s2 INNER JOIN @SomeTable s1 ON s2.SomeIdPk = s1.SomeIdPk WHERE s1.MainTablePkId = m.MainTablePkId) FROM @MainTable m Above given script is just sample. I have long list of columns in SELECT and around 12+ columns in Sub Query. In my From clause there are around 8 tables. To fetch 2000 records full query take 21 seconds and if I remove Subquiries it just take 4 seconds. I have tried to optimize query using 'Database Engine Tuning Advisor' and on adding new advised indexes and statistics but these changes make query time even bad. Note: As I have mentioned that this is test data to explain my question the real data has lot of tables joins columns but without Sub-Query the results us fine. Any help thanks.

    Read the article

  • Jquery Datepicker with XML file

    - by matt
    an extension of my last question, http://stackoverflow.com/questions/2562986/getdate-with-jquery-datepicker , I am trying to use the jquery datepicker to load specific info from xml file dependent on the date selected by the user. Similar code but i am trying to load and parse an xml file to read contents of the file for the particular date. In a perfect world the user would tap a date and below the datepicker html output would give the user specific times for the selected date instead of my last project of an image. my probelm is nothing is loading, so my question is what am i doing wrong? my code is as follows <!DOCTYPE html> <link type="text/css" href="css/ui-darkness/jquery-ui-1.8.custom.css" rel="stylesheet" /> <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="js/jquery-ui-1.8.custom.min.js"></script> <script type="text/javascript"> $(function(){ // Datepicker $('#datepicker').datepicker({ dateFormat: 'yy-mm-dd', inline: true, minDate: new Date(2010, 1 - 1, 1), maxDate:new Date(2010, 12 - 1, 31), altField: '#datepicker_value', onSelect: function(){ var day1 = $("#datepicker").datepicker('getDate').getDate(); var month1 = $("#datepicker").datepicker('getDate').getMonth() + 1; var year1 = $("#datepicker").datepicker('getDate').getFullYear(); var fullDate = year1 + "" + month1 + "" + day1; //var str_output ="<img src=\"http://69.89.20.27/images/a" + fullDate +".png\" width=\"100%\"/>"; //"<h1>"+fullDate+"</h1>"; //"<img src=\"http://69.*.*.*/images/a" + fullDate +".png\"/>"; //$('#page_output').html(str_output); var doc = loadXMLDoc('date.xml'); // loading the XML file var el = doc.getElementsByTagName('_'+date); // retrieving the elements corrsponding to a date, eg: _20100103 var page_output = document.getElementById('page_output'); if(el.length >= 1) { // matched XML data found for the specified date var dt = el[0].getElementsByTagName('date'); var great_times = el[0].getElementsByTagName('great_times'); var good_times = el[0].getElementsByTagName('good_times'); var str_output = "<h1><center>" + dt[0].childNodes[0].nodeValue + "</center></h1><br/><br>"; str_output += "<b>Excellent Times:</b><br> " + great_times[0].childNodes[0].nodeValue + "<br/><br>"; str_output += "<b>Good Times:</b><br> " + good_times[0].childNodes[0].nodeValue + "<br/><br>"; $('#page_output').html(str_output);// writing the results to the div element (page_out) } else { alert("Sorry","Action not allowed on this page"); page_output.innerHTML = ''; // No XML data found for the selected date reloadmainwDate(); return false; } return true; } }); //hover states on the static widgets $('#dialog_link, ul#icons li').hover( function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); } ); }); //var img_date = .datepicker('getDate'); //var day1 = $("#datepicker").datepicker('getDate').getDate(); //var month1 = $("#datepicker").datepicker('getDate').getMonth() + 1; //var year1 = $("#datepicker").datepicker('getDate').getFullYear(); //var fullDate = year1 + "-" + month1 + "-" + day1; //var date = $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }); //var str_output = "<h1><center><p>"+ date + "</p></center></h1>"; //$('#page_output')[0].innerHTML = str_output; // writing the results to the div element (page_out) </script> <script> function loadXMLDoc(dname) { var xmlDoc; // IE 5 and IE 6 if(typeof ActiveXObject != 'undefined') { xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async=false; xmlDoc.load(dname); return xmlDoc; } else if (window.XMLHttpRequest) // firefox { xmlDoc=new window.XMLHttpRequest(); xmlDoc.open("GET",dname,false); xmlDoc.send(""); return xmlDoc.responseXML; } alert("Error loading document"); return null; } <!-- Datepicker --> <div id="datepicker"></div> <!-- Highlight / Error --> <div id="page_output"></div> </body>

    Read the article

  • CONVERT(int, (datepart(month, @search)), (datepart(day, @search)), DateAdd(year, Years.Year - (datepart(year, @search)))

    - by MyHeadHurts
    In the query the top part is getting all the years that will run in the stored procedure. Works fine But at first i just wanted to run the queries for yesterdays date for all the years, but now i realized i want the user to select a date that will be in a parameter @search Booked <= CONVERT(int,DateAdd(year, Years.Year - Year(getdate()), DateAdd(day, DateDiff(day, 2, getdate()), 1))) this should be easy because normally it would just be Booked <= CONVERT(int,@search) but the problem is i want to do something like a Booked <= CONVERT(int, (datepart(month, @search)), (datepart(day, @search)), DateAdd(year, Years.Year - (datepart(year, @search))) would something like that work i dont need to worry about subtracting days but i still need to worry about the years WITH Years AS ( SELECT DATEPART(year, GETDATE()) [Year] UNION ALL SELECT [Year]-1 FROM Years WHERE [Year]>@YearToGet ), q_00 as ( select DIVISION , DYYYY , sum(PARTY) as asofPAX , sum(APRICE) as asofSales from dbo.B101BookingsDetails INNER JOIN Years ON B101BookingsDetails.DYYYY = Years.Year where Booked <= CONVERT(int,DateAdd(year, Years.Year - Year(getdate()), DateAdd(day, DateDiff(day, 2, getdate()), 1))) and DYYYY = Years.Year group by DIVISION, DYYYY, years.year having DYYYY = years.year ),

    Read the article

  • Create a date from Credit Card expire in MMYY format

    - by Sophtware
    I need to convert a credit card expire field from MMYY to a date field I can use in a MS SQL query so I can compute when credit cards are expiring in the future. Basically, I need to go from MMYY to MM/DD/YYYY, where the day part could just be '01' (the first of the month). I'm looking for credit cards that are expiring next month from a database. The problem I'm running into is when next month is the first month of the next year. Here's the code I have for determining expired card: (CAST(SUBSTRING(CCExpire,3,2) as int) + 2000 < YEAR(GETDATE())) or ( (CAST(SUBSTRING(CCExpire,3,2) as int) + 2000 = YEAR(GETDATE())) AND (CAST(SUBSTRING(CCExpire,1,2) as int) < MONTH(GETDATE())) ) And here's the code for cards expiring this month: (CAST(SUBSTRING(CCExpire,3,2) as int) + 2000 = YEAR(GETDATE())) AND (CAST(SUBSTRING(CCExpire,1,2) as int) = MONTH(GETDATE())) Now I need code for cards expiring next month...

    Read the article

  • Error in SQL. Can not find it.

    - by kmsboy
    Error in SQL. Can not find it. DECLARE @year VARCHAR (4), @month VARCHAR (2), @day VARCHAR (2), @weekday VARCHAR (2), @hour VARCHAR (2), @archivePath VARCHAR (128), @archiveName VARCHAR (128), @archiveFullName VARCHAR (128) SET @year = CAST(DATEPART(yyyy, GETDATE()) AS VARCHAR) SET @month = CAST(DATEPART(mm, GETDATE()) AS VARCHAR) SET @day = CAST(DATEPART(dd, GETDATE()) AS VARCHAR) SET @weekday = CAST(DATEPART (dw, GETDATE()) AS VARCHAR) SET @hour = CAST(DATEPART (hh, GETDATE()) AS VARCHAR) SET @archivePath = 'd:\1c_new\backupdb\' SET @archiveName = 'TransactionLog_' + @year + '_' + @month + '_' + @day + '_' + @hour + '.bak' SET @archiveFullName = @archivePath + @archiveName BACKUP LOG [xxx] TO DISK = @archiveFullName WITH INIT , NOUNLOAD , NAME = N'?????????? ??? ??????????', SKIP , STATS = 10, DESCRIPTION = N'?????????? ??? ??????????', NOFORMAT

    Read the article

  • Setting database-agnostic default column timestamp using Hibernate

    - by unsquared
    I'm working on a java project full of Hibernate (3.3.1) mapping files that have the following sort of declaration for most domain objects. <property name="dateCreated" generated="insert"> <column name="date_created" default="getdate()" /> </property> The problem here is that getdate() is an MSSQL specific function, and when I'm using something like H2 to test subsections of the project, H2 screams that getdate() isn't a recognized function. It's own timestamping function is current_timestamp(). I'd like to be able to keep working with H2 for testing, and wanted to know whether there was a way of telling Hibernate "use this database's own mechanism for retrieving the current timestamp". With H2, I've come up with the following solution. CREATE ALIAS getdate AS $$ java.util.Date now() { return new java.util.Date(); } $$; CALL getdate(); It works, but is obviously H2 specific. I've tried extending H2Dialect and registering the function getdate(), but that doesn't seem to be invoked when Hibernate is creating tables. Is it possible to abstract the idea of a default timestamp away from the specific database engine?

    Read the article

  • Altering a Column Which has a Default Constraint

    - by Dinesh Asanka
    Setting up a default column is a common task for  developers.  But, are we naming those default constraints explicitly? In the below  table creation, for the column, sys_DateTime the default value Getdate() will be allocated. CREATE TABLE SampleTable (ID int identity(1,1), Sys_DateTime Datetime DEFAULT getdate() ) We can check the relevant information from the system catalogs from following query. SELECT sc.name TableName, dc.name DefaultName, dc.definition, OBJECT_NAME(dc.parent_object_id) TableName, dc.is_system_named  FROM sys.default_constraints dc INNER JOIN sys.columns sc ON dc.parent_object_id = sc.object_id AND dc.parent_column_id = sc.column_id and results would be: Most of the above columns are self-explanatory. The last column, is_system_named, is to identify whether the default name was given by the system. As you know, in the above case, since we didn’t provide  any default name, the  system will generate a default name for you. But the problem with these names is that they can differ from environment to environment.  If example if I create this table in different table the default name could be DF__SampleTab__Sys_D__7E6CC920 Now let us create another default and explicitly name it: CREATE TABLE SampleTable2 (ID int identity(1,1), Sys_DateTime Datetime )   ALTER TABLE SampleTable2 ADD CONSTRAINT DF_sys_DateTime_Getdate DEFAULT( Getdate()) FOR Sys_DateTime If we run the previous query again we will be returned the below output. And you can see that last created default name has 0 for is_system_named. Now let us say I want to change the data type of the sys_DateTime column to something else: ALTER TABLE SampleTable2 ALTER COLUMN Sys_DateTime Date This will generate the below error: Msg 5074, Level 16, State 1, Line 1 The object ‘DF_sys_DateTime_Getdate’ is dependent on column ‘Sys_DateTime’. Msg 4922, Level 16, State 9, Line 1 ALTER TABLE ALTER COLUMN Sys_DateTime failed because one or more objects access this column. This means, you need to drop the default constraint before altering it: ALTER TABLE [dbo].[SampleTable2] DROP CONSTRAINT [DF_sys_DateTime_Getdate] ALTER TABLE SampleTable2 ALTER COLUMN Sys_DateTime Date   ALTER TABLE [dbo].[SampleTable2] ADD CONSTRAINT [DF_sys_DateTime_Getdate] DEFAULT (getdate()) FOR [Sys_DateTime] If you have a system named default constraint that can differ from environment to environment and so you cannot drop it as before, you can use the below code template: DECLARE @defaultname VARCHAR(255) DECLARE @executesql VARCHAR(1000)   SELECT @defaultname = dc.name FROM sys.default_constraints dc INNER JOIN sys.columns sc ON dc.parent_object_id = sc.object_id AND dc.parent_column_id = sc.column_id WHERE OBJECT_NAME (parent_object_id) = 'SampleTable' AND sc.name ='Sys_DateTime' SET @executesql = 'ALTER TABLE SampleTable DROP CONSTRAINT ' + @defaultname EXEC( @executesql) ALTER TABLE SampleTable ALTER COLUMN Sys_DateTime Date ALTER TABLE [dbo].[SampleTable] ADD DEFAULT (Getdate()) FOR [Sys_DateTime]

    Read the article

  • Database Backup History From MSDB in a pivot table

    - by steveh99999
    I knocked up a nice little query to display backup history for each database in a pivot table format.I wanted to display the most recent full, differential, and transaction log backup for each database. Here's the SQL :-WITH backupCTE AS (SELECT name, recovery_model_desc, d AS 'Last Full Backup', i AS 'Last Differential Backup', l AS 'Last Tlog Backup' FROM ( SELECT db.name, db.recovery_model_desc,type, backup_finish_date FROM master.sys.databases db LEFT OUTER JOIN msdb.dbo.backupset a ON a.database_name = db.name WHERE db.state_desc = 'ONLINE' ) AS Sourcetable   PIVOT (MAX (backup_finish_date) FOR type IN (D,I,L) ) AS MostRecentBackup ) SELECT * FROM backupCTE Gives output such as this :-  With this query, I can then build up some straightforward queries to ensure backups are scheduled and running as expected -For example, the following logic can be used ;-  - WHERE [Last Full Backup] IS NULL) - ie database has never been backed up.. - WHERE [Last Tlog Backup] < DATEDIFF(mm,GETDATE(),-60) AND recovery_model_desc <> 'SIMPLE') - transction log not backed up in last 60 minutes. - WHERE [Last Full Backup] < DATEDIFF(dd,GETDATE(),-1) AND [Last Differential Backup] < [Last Full Backup]) -- no backup in last day.- WHERE [Last Differential Backup] < DATEDIFF(dd,GETDATE(),-1) AND [Last Full Backup] < DATEDIFF(dd,GETDATE(),-8) ) -- no differential backup in last day when last full backup is over 8 days old.   

    Read the article

  • Everytime user types , in my text box i want it to become ',' or help me do it using a parameter

    - by MyHeadHurts
    I am using a vb.net textbox to become part of my IN sql statement in my program I tryed to use a parameter and it didn't work here is my code TextBox1.Text = "'Cruises','Caribbean and Mexico','CentralSouth America', 'Europe','Far East','France','Italy','London/UK','Middle East/Africa','South Pacific','Spain/Portugal','USA/Canada'" the default value of my textbox although the user can edit the textbox, but they would need to type the ',' which i would rather them just type , . and my other code is If RadioButtonList1.SelectedValue = "Sales" And CheckBox1.Checked = False Then 'saocmd1.CommandText = "SELECT dbo.B605SaleAsOfAdvancedMaster.SDESCR, dbo.B605SaleAsOfAdvancedMaster.DYYYY, dbo.B605SaleAsOfAdvancedMaster.AsOFSales, dbo.B605SaleAsOfAdvancedMaster.ASOFPAX, dbo.B605SaleAsOfAdvancedMaster.YESales, dbo.B605SaleAsOfAdvancedMaster.YEPAX, dbo.B604SalesAsOfAdvanced.Sales AS CurrentSales, dbo.B604SalesAsOfAdvanced.PAX AS CurrentPAX FROM B604SalesAsOfAdvanced INNER JOIN B605SaleAsOfAdvancedMaster ON dbo.B605SaleAsOfAdvancedMaster.SDESCR = B604SalesAsOfAdvanced.SDESCR WHERE (B605SaleAsOfAdvancedMaster.DYYYY =" & DropDownList1.SelectedValue & ") AND (B604SalesAsOfAdvanced.DYYYY = (DatePart(year, GetDate()) +1)) order by B605SaleAsOfAdvancedMaster.SDESCR" saocmd1.CommandText = "SELECT dbo.B605SaleAsOfAdvancedMaster.SDESCR, dbo.B605SaleAsOfAdvancedMaster.DYYYY, dbo.B605SaleAsOfAdvancedMaster.AsOFSales, dbo.B605SaleAsOfAdvancedMaster.ASOFPAX, dbo.B605SaleAsOfAdvancedMaster.YESales, dbo.B605SaleAsOfAdvancedMaster.YEPAX, dbo.B604SalesAsOfAdvanced.Sales AS CurrentSales, dbo.B604SalesAsOfAdvanced.PAX AS CurrentPAX FROM B604SalesAsOfAdvanced INNER JOIN B605SaleAsOfAdvancedMaster ON dbo.B605SaleAsOfAdvancedMaster.SDESCR = B604SalesAsOfAdvanced.SDESCR WHERE (B605SaleAsOfAdvancedMaster.DYYYY =@Dyyyy) AND (B604SalesAsOfAdvanced.DYYYY = (DatePart(year, GetDate()) +1)) and dbo.B605SaleAsOfAdvancedMaster.SDESCR in ('Cruises','Caribbean and Mexico','CentralSouth America', 'Europe','Far East','France','Italy','London/UK','Middle East/Africa','South Pacific','Spain/Portugal','USA/Canada') order by B605SaleAsOfAdvancedMaster.SDESCR" Label2.Text = "Sales" ElseIf RadioButtonList1.SelectedValue = "NetSales" And CheckBox1.Checked = False Then saocmd1.CommandText = "SELECT dbo.B605SaleAsOfAdvancedMaster.SDESCR, dbo.B605SaleAsOfAdvancedMaster.DYYYY, (ISNULL(dbo.B605SaleAsOfAdvancedMaster.AsOFNET,0) + (ISNULL(dbo.B605SaleAsOfAdvancedMaster.AsOFOther,0))) as AsofSales, dbo.B605SaleAsOfAdvancedMaster.ASOFPAX, (ISNULL(dbo.B605SaleAsOfAdvancedMaster.YENET,0) + (ISNULL(dbo.B605SaleAsOfAdvancedMaster.YEOther,0))) as YESales, dbo.B605SaleAsOfAdvancedMaster.YEPAX, (ISNULL(dbo.B604SalesAsOfAdvanced.netSales,0) + (ISNULL(dbo.B604SalesAsOfAdvanced.OtherSales,0))) as CurrentSales, dbo.B604SalesAsOfAdvanced.PAX AS CurrentPAX FROM B604SalesAsOfAdvanced INNER JOIN B605SaleAsOfAdvancedMaster ON dbo.B605SaleAsOfAdvancedMaster.SDESCR = B604SalesAsOfAdvanced.SDESCR WHERE (B605SaleAsOfAdvancedMaster.DYYYY =@Dyyyy) AND (B604SalesAsOfAdvanced.DYYYY = (DatePart(year, GetDate()) +1)) and dbo.B605SaleAsOfAdvancedMaster.SDESCR in ('Cruises','Caribbean and Mexico','CentralSouth America', 'Europe','Far East','France','Italy','London/UK','Middle East/Africa','South Pacific','Spain/Portugal','USA/Canada') order by B605SaleAsOfAdvancedMaster.SDESCR" Label2.Text = "Net Sales" ElseIf RadioButtonList1.SelectedValue = "INSSales" And CheckBox1.Checked = False Then saocmd1.CommandText = "SELECT dbo.B605SaleAsOfAdvancedMaster.SDESCR, dbo.B605SaleAsOfAdvancedMaster.DYYYY, ISNULL(dbo.B605SaleAsOfAdvancedMaster.AsOFINS,0)as AsofSales, dbo.B605SaleAsOfAdvancedMaster.ASOFPAX, ISNULL(dbo.B605SaleAsOfAdvancedMaster.YEINS,0) as YESales, dbo.B605SaleAsOfAdvancedMaster.YEPAX, ISNULL(dbo.B604SalesAsOfAdvanced.INSSales,0) as CurrentSales, dbo.B604SalesAsOfAdvanced.PAX AS CurrentPAX FROM B604SalesAsOfAdvanced INNER JOIN B605SaleAsOfAdvancedMaster ON dbo.B605SaleAsOfAdvancedMaster.SDESCR = B604SalesAsOfAdvanced.SDESCR WHERE (B605SaleAsOfAdvancedMaster.DYYYY =@Dyyyy) AND (B604SalesAsOfAdvanced.DYYYY = (DatePart(year, GetDate()) +1)) and dbo.B605SaleAsOfAdvancedMaster.SDESCR in ('Cruises','Caribbean and Mexico','CentralSouth America', 'Europe','Far East','France','Italy','London/UK','Middle East/Africa','South Pacific','Spain/Portugal','USA/Canada') order by B605SaleAsOfAdvancedMaster.SDESCR" Label2.Text = "Insurance Sales" ElseIf RadioButtonList1.SelectedValue = "CXSales" And CheckBox1.Checked = False Then saocmd1.CommandText = "SELECT dbo.B605SaleAsOfAdvancedMaster.SDESCR, dbo.B605SaleAsOfAdvancedMaster.DYYYY, ISNULL(dbo.B605SaleAsOfAdvancedMaster.AsOFCX,0)as AsofSales, dbo.B605SaleAsOfAdvancedMaster.ASOFPAX, ISNULL(dbo.B605SaleAsOfAdvancedMaster.YECX,0) as YESales, dbo.B605SaleAsOfAdvancedMaster.YEPAX, ISNULL(dbo.B604SalesAsOfAdvanced.CXSales,0) as CurrentSales, dbo.B604SalesAsOfAdvanced.PAX AS CurrentPAX FROM B604SalesAsOfAdvanced INNER JOIN B605SaleAsOfAdvancedMaster ON dbo.B605SaleAsOfAdvancedMaster.SDESCR = B604SalesAsOfAdvanced.SDESCR WHERE (B605SaleAsOfAdvancedMaster.DYYYY =@Dyyyy) AND (B604SalesAsOfAdvanced.DYYYY = (DatePart(year, GetDate()) +1)) and dbo.B605SaleAsOfAdvancedMaster.SDESCR in ('Cruises','Caribbean and Mexico','CentralSouth America', 'Europe','Far East','France','Italy','London/UK','Middle East/Africa','South Pacific','Spain/Portugal','USA/Canada') order by B605SaleAsOfAdvancedMaster.SDESCR" Label2.Text = "Canceled Sales" ElseIf RadioButtonList1.SelectedValue = "Sales" And CheckBox1.Checked = True Then saocmd1.CommandText = "SELECT dbo.B605SaleAsOfAdvancedMaster.SDESCR, dbo.B605SaleAsOfAdvancedMaster.DYYYY, dbo.B605SaleAsOfAdvancedMaster.AsOFSales, dbo.B605SaleAsOfAdvancedMaster.ASOFPAX, dbo.B605SaleAsOfAdvancedMaster.YESales, dbo.B605SaleAsOfAdvancedMaster.YEPAX, dbo.B604SalesAsOfAdvanced.Sales AS CurrentSales, dbo.B604SalesAsOfAdvanced.PAX AS CurrentPAX FROM B604SalesAsOfAdvanced INNER JOIN B605SaleAsOfAdvancedMaster ON dbo.B605SaleAsOfAdvancedMaster.SDESCR = B604SalesAsOfAdvanced.SDESCR WHERE (B605SaleAsOfAdvancedMaster.DYYYY =@Dyyyy) AND (B604SalesAsOfAdvanced.DYYYY = (DatePart(year, GetDate()) +1)) and dbo.B605SaleAsOfAdvancedMaster.SDESCR in (" & TextBox1.Text & ") order by B605SaleAsOfAdvancedMaster.SDESCR" Label2.Text = "Sales" ElseIf RadioButtonList1.SelectedValue = "NetSales" And CheckBox1.Checked = True Then saocmd1.CommandText = "SELECT dbo.B605SaleAsOfAdvancedMaster.SDESCR, dbo.B605SaleAsOfAdvancedMaster.DYYYY, (ISNULL(dbo.B605SaleAsOfAdvancedMaster.AsOFNET,0) + (ISNULL(dbo.B605SaleAsOfAdvancedMaster.AsOFOther,0))) as AsofSales, dbo.B605SaleAsOfAdvancedMaster.ASOFPAX, (ISNULL(dbo.B605SaleAsOfAdvancedMaster.YENET,0) + (ISNULL(dbo.B605SaleAsOfAdvancedMaster.YEOther,0))) as YESales, dbo.B605SaleAsOfAdvancedMaster.YEPAX, (ISNULL(dbo.B604SalesAsOfAdvanced.netSales,0) + (ISNULL(dbo.B604SalesAsOfAdvanced.OtherSales,0))) as CurrentSales, dbo.B604SalesAsOfAdvanced.PAX AS CurrentPAX FROM B604SalesAsOfAdvanced INNER JOIN B605SaleAsOfAdvancedMaster ON dbo.B605SaleAsOfAdvancedMaster.SDESCR = B604SalesAsOfAdvanced.SDESCR WHERE (B605SaleAsOfAdvancedMaster.DYYYY =@Dyyyy) AND (B604SalesAsOfAdvanced.DYYYY = (DatePart(year, GetDate()) +1)) and dbo.B605SaleAsOfAdvancedMaster.SDESCR in (" & TextBox1.Text & ") order by B605SaleAsOfAdvancedMaster.SDESCR" Label2.Text = "Net Sales" ElseIf RadioButtonList1.SelectedValue = "INSSales" And CheckBox1.Checked = True Then saocmd1.CommandText = "SELECT dbo.B605SaleAsOfAdvancedMaster.SDESCR, dbo.B605SaleAsOfAdvancedMaster.DYYYY, ISNULL(dbo.B605SaleAsOfAdvancedMaster.AsOFINS,0)as AsofSales, dbo.B605SaleAsOfAdvancedMaster.ASOFPAX, ISNULL(dbo.B605SaleAsOfAdvancedMaster.YEINS,0) as YESales, dbo.B605SaleAsOfAdvancedMaster.YEPAX, ISNULL(dbo.B604SalesAsOfAdvanced.INSSales,0) as CurrentSales, dbo.B604SalesAsOfAdvanced.PAX AS CurrentPAX FROM B604SalesAsOfAdvanced INNER JOIN B605SaleAsOfAdvancedMaster ON dbo.B605SaleAsOfAdvancedMaster.SDESCR = B604SalesAsOfAdvanced.SDESCR WHERE (B605SaleAsOfAdvancedMaster.DYYYY =@Dyyyy) AND (B604SalesAsOfAdvanced.DYYYY = (DatePart(year, GetDate()) +1)) and dbo.B605SaleAsOfAdvancedMaster.SDESCR in (" & TextBox1.Text & ") order by B605SaleAsOfAdvancedMaster.SDESCR" Label2.Text = "Insurance Sales" ElseIf RadioButtonList1.SelectedValue = "CXSales" And CheckBox1.Checked = True Then saocmd1.CommandText = "SELECT dbo.B605SaleAsOfAdvancedMaster.SDESCR, dbo.B605SaleAsOfAdvancedMaster.DYYYY, ISNULL(dbo.B605SaleAsOfAdvancedMaster.AsOFCX,0)as AsofSales, dbo.B605SaleAsOfAdvancedMaster.ASOFPAX, ISNULL(dbo.B605SaleAsOfAdvancedMaster.YECX,0) as YESales, dbo.B605SaleAsOfAdvancedMaster.YEPAX, ISNULL(dbo.B604SalesAsOfAdvanced.CXSales,0) as CurrentSales, dbo.B604SalesAsOfAdvanced.PAX AS CurrentPAX FROM B604SalesAsOfAdvanced INNER JOIN B605SaleAsOfAdvancedMaster ON dbo.B605SaleAsOfAdvancedMaster.SDESCR = B604SalesAsOfAdvanced.SDESCR WHERE (B605SaleAsOfAdvancedMaster.DYYYY =@Dyyyy) AND (B604SalesAsOfAdvanced.DYYYY = (DatePart(year, GetDate()) +1)) and dbo.B605SaleAsOfAdvancedMaster.SDESCR in (" & TextBox1.Text & ") order by B605SaleAsOfAdvancedMaster.SDESCR" Label2.Text = "Canceled Sales" End If Basically what is happening is, if a certain radio button is selected and the user didn't click the checkbox the default regions are included and they are hardcoded because the query runs much faster. if the user did click the checkbox then the textbox where they type the specific regions shows up and it will run the query that includes the dbo.B605SaleAsOfAdvancedMaster.SDESCR in (" & TextBox1.Text & ") If you can somehow do this using parameters and not with the textbox1.text in the query it will run much faster for me thanks for your help

    Read the article

  • SQL SERVER – Find Weekend and Weekdays from Datetime in SQL Server 2012

    - by pinaldave
    Yesterday we had very first SQL Bangalore User Group meeting and I was asked following question right after the session. “How do we know if today is a weekend or weekday using SQL Server Functions?” Well, I assume most of us are using SQL Server 2012 so I will suggest following solution. I am using SQL Server 2012′s CHOOSE function. It is SELECT GETDATE() Today, DATENAME(dw, GETDATE()) DayofWeek, CHOOSE(DATEPART(dw, GETDATE()), 'WEEKEND','Weekday', 'Weekday','Weekday','Weekday','Weekday','WEEKEND') WorkDay GO You can use the choose function on table as well. Here is the quick example of the same. USE AdventureWorks2012 GO SELECT A.ModifiedDate, DATENAME(dw, A.ModifiedDate) DayofWeek, CHOOSE(DATEPART(dw, A.ModifiedDate), 'WEEKEND','Weekday', 'Weekday','Weekday','Weekday','Weekday','WEEKEND') WorkDay FROM [Person].[Address] A GO If you are using an earlier version of the SQL Server you can use a CASE statement instead of CHOOSE function. Please read my earlier article which discusses CHOOSE function and CASE statements. Logical Function – CHOOSE() – A Quick Introduction Reference:  Pinal Dave (http://blog.SQLAuthority.com) Filed under: PostADay, SQL, SQL Authority, SQL DateTime, SQL Function, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • Date and Time Support in SQL Server 2008

    - by Aamir Hasan
      Using the New Date and Time Data Types Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0in; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} 1.       The new date and time data types in SQL Server 2008 offer increased range and precision and are ANSI SQL compatible. 2.       Separate date and time data types minimize storage space requirements for applications that need only date or time information. Moreover, the variable precision of the new time data type increases storage savings in exchange for reduced accuracy. 3.       The new data types are mostly compatible with the original date and time data types and use the same Transact-SQL functions. 4.       The datetimeoffset data type allows you to handle date and time information in global applications that use data that originates from different time zones. SELECT c.name, p.* FROM politics pJOIN country cON p.country = c.codeWHERE YEAR(Independence) < 1753ORDER BY IndependenceGO8.    Highlight the SELECT statement and click Execute ( ) to show the use of some of the date functions.T-SQLSELECT c.name AS [Country Name],        CONVERT(VARCHAR(12), p.Independence, 107) AS [Independence Date],       DATEDIFF(YEAR, p.Independence, GETDATE()) AS [Years Independent (appox)],       p.GovernmentFROM politics pJOIN country cON p.country = c.codeWHERE YEAR(Independence) < 1753ORDER BY IndependenceGO10.    Select the SET DATEFORMAT statement and click Execute ( ) to change the DATEFORMAT to day-month-year.T-SQLSET DATEFORMAT dmyGO11.    Select the DECLARE and SELECT statements and click Execute ( ) to show how the datetime and datetime2 data types interpret a date literal.T-SQLSET DATEFORMAT dmyDECLARE @dt datetime = '2008-12-05'DECLARE @dt2 datetime2 = '2008-12-05'SELECT MONTH(@dt) AS [Month-Datetime], DAY(@dt)     AS [Day-Datetime]SELECT MONTH(@dt2) AS [Month-Datetime2], DAY(@dt2)     AS [Day-Datetime2]GO12.    Highlight the DECLARE and SELECT statements and click Execute ( ) to use integer arithmetic on a datetime variable.T-SQLDECLARE @dt datetime = '2008-12-05'SELECT @dt + 1GO13.    Highlight the DECLARE and SELECT statements and click Execute ( ) to show how integer arithmetic is not allowed for datetime2 variables.T-SQLDECLARE @dt2 datetime = '2008-12-05'SELECT @dt2 + 1GO14.    Highlight the DECLARE and SELECT statements and click Execute ( ) to show how to use DATE functions to do simple arithmetic on datetime2 variables.T-SQLDECLARE @dt2 datetime2(7) = '2008-12-05'SELECT DATEADD(d, 1, @dt2)GO15.    Highlight the DECLARE and SELECT statements and click Execute ( ) to show how the GETDATE function can be used with both datetime and datetime2 data types.T-SQLDECLARE @dt datetime = GETDATE();DECLARE @dt2 datetime2(7) = GETDATE();SELECT @dt AS [GetDate-DateTime], @dt2 AS [GetDate-DateTime2]GO16.    Draw attention to the values returned for both columns and how they are equal.17.    Highlight the DECLARE and SELECT statements and click Execute ( ) to show how the SYSDATETIME function can be used with both datetime and datetime2 data types.T-SQLDECLARE @dt datetime = SYSDATETIME();DECLARE @dt2 datetime2(7) = SYSDATETIME();SELECT @dt AS [Sysdatetime-DateTime], @dt2     AS [Sysdatetime-DateTime2]GO18.    Draw attention to the values returned for both columns and how they are different.Programming Global Applications with DateTimeOffset 2.    If you have not previously created the SQLTrainingKitDB database while completing another demo in this training kit, highlight the CREATE DATABASE statement and click Execute ( ) to do so now.T-SQLCREATE DATABASE SQLTrainingKitDBGO3.    Select the USE and CREATE TABLE statements and click Execute ( ) to create table datetest in the SQLTrainingKitDB database.T-SQLUSE SQLTrainingKitDBGOCREATE TABLE datetest (  id integer IDENTITY PRIMARY KEY,  datetimecol datetimeoffset,  EnteredTZ varchar(40)); Reference:http://www.microsoft.com/downloads/details.aspx?FamilyID=E9C68E1B-1E0E-4299-B498-6AB3CA72A6D7&displaylang=en   

    Read the article

  • Zend Date -- day difference

    - by Nisanth
    Hi All, I have the below line of codes $day1 = new Zend_Date('2010-03-01', 'YYYY-mm-dd'); $day2 = new Zend_Date('2010-03-05', 'YYYY-mm-dd'); $dateDiff = $day2->getDate()->get(Zend_Date::TIMESTAMP) - $day1->getDate()->get(Zend_Date::TIMESTAMP); $days = floor((($dateDiff / 60) / 60) / 24); return $days; this will return 4 But if gave $day1 = new Zend_Date('2010-02-28', 'YYYY-mm-dd'); $day2 = new Zend_Date('2010-03-01', 'YYYY-mm-dd'); $dateDiff = $day2->getDate()->get(Zend_Date::TIMESTAMP) - $day1->getDate()->get(Zend_Date::TIMESTAMP); $days = floor((($dateDiff / 60) / 60) / 24); return $days; it will return -27 .. how will i get right answer

    Read the article

  • javascript date and loop check

    - by StealthRT
    Hey all, this is the code i have to check for a day thats equal to the list of days in the comma seperated list: for(var i = 0; i < daysHidden.length; i++){ if (daysHidden[i] == d.getDate()); { alert(daysHidden[i] + '=' + d.getDate()); } } the daysHidden = 1 (its the only thing in the list April 1st is already gone and todays the 2nd so 1 is the only one in the list) and d.getDate() has 1-30 (for april) When i run the code, however, it keeps looping through the if code when it should only loop once (when it finds that 1=1 However, i keep getting the alert box that says: 1=1 1=2 1=3 etc.... 1=30 So i do not know what i am doing incorrect? I already tried putting them as strings: if (daysHidden[i].ToString == d.getDate().ToString); But that doesnt seem to work.... Any help would be great :) David

    Read the article

  • Use a certain select statement in a stored procedure depending on the Exec statement

    - by MyHeadHurts
    Alright so i am not even sure if this is possible I have a q_00 and q_01 and q_02 which are all in my stored procedure. then on the bottom i have 3 select statements that select a certain catagory for example Sales,Net Sales and INS sales What i want to be able to do is if the user types exec (name of my sp) (sales) (and a year which is the @yearparameter) it will run the sales select statement If they type Exec (name of my SP) netsales (@Yeartoget) it will show the net sales is this possible or do i need multiple stored procedures ALTER PROCEDURE [dbo].[casof] @YearToGet int as ; with q_00 as ( select DIVISION , SDESCR , DYYYY , sum(APRICE) as asofSales , sum(PARTY) as asofPAX , sum(NetAmount) as asofNetSales , sum(InsAmount) as asofInsSales , sum(CancelRevenue) as asofCXSales , sum(OtherAmount) as asofOtherSales , sum(CXVALUE) as asofCXValue from dbo.B101BookingsDetails where Booked <= CONVERT(int,DateAdd(year, @YearToGet - Year(getdate()), DateAdd(day, DateDiff(day, 1, getdate()), 0))) and DYYYY = @YearToGet group by DIVISION, SDESCR, DYYYY ), q_01 as ( select DIVISION , SDESCR , DYYYY , sum(APRICE) as YESales , sum(PARTY) as YEPAX , sum(NetAmount) as YENetSales , sum(InsAmount) as YEInsSales , sum(CancelRevenue) as YECXSales , sum(OtherAmount) as YEOtherSales , sum(CXVALUE) as YECXValue from dbo.B101BookingsDetails where DYYYY=@YearToGet group by DIVISION, SDESCR, DYYYY ), q_02 as ( select DIVISION , SDESCR , DYYYY , sum(APRICE) as CurrentSales , sum(PARTY) as CurrentPAX , sum(NetAmount) as CurrentNetSales , sum(InsAmount) as CurrentInsSales , sum(CancelRevenue) as CurrentCXSales , sum(OtherAmount) as CurrentOtherSales , sum(CXVALUE) as CurrentCXValue from dbo.B101BookingsDetails where Booked <= CONVERT(int,DateAdd(year, (year( getdate() )) - Year(getdate()), DateAdd(day, DateDiff(day, 1, getdate()), 0))) and DYYYY = (year( getdate() )) group by DIVISION, SDESCR, DYYYY ) select a.DIVISION , a.SDESCR , a.DYYYY , asofSales , asofPAX , YESales , YEPAX , CurrentSales , CurrentPAX , asofsales/ ISNULL(NULLIF(yesales,0),1) as percentsales , asofpax/yepax as percentpax ,currentsales/ISNULL(NULLIF((asofsales/ISNULL(NULLIF(yesales,0),1)),0),1) as projectedsales ,currentpax/ISNULL(NULLIF((asofpax/ISNULL(NULLIF(yepax,0),1)),0),1) as projectedpax from q_00 as a join q_01 as b on (b.DIVISION = a.DIVISION and b.SDESCR = a.SDESCR and b.DYYYY = a.DYYYY) join q_02 as c on (b.DIVISION = c.DIVISION and b.SDESCR = c.SDESCR) order by a.DIVISION, a.SDESCR, a.DYYYY ; select a.DIVISION , a.SDESCR , a.DYYYY , asofPAX , asofNetSales , YEPAX , YENetSales , CurrentPAX , CurrentNetSales , asofnetsales/ ISNULL(NULLIF(yenetsales,0),1) as percentnetsales , asofpax/yepax as percentpax ,currentnetsales/ISNULL(NULLIF((asofnetsales/ISNULL(NULLIF(yenetsales,0),1)),0),1) as projectednetsales ,currentpax/ISNULL(NULLIF((asofpax/ISNULL(NULLIF(yepax,0),1)),0),1) as projectedpax from q_00 as a join q_01 as b on (b.DIVISION = a.DIVISION and b.SDESCR = a.SDESCR and b.DYYYY = a.DYYYY) join q_02 as c on (b.DIVISION = c.DIVISION and b.SDESCR = c.SDESCR) order by a.DIVISION, a.SDESCR, a.DYYYY ; select a.DIVISION , a.SDESCR , a.DYYYY , asofPAX , asofInsSales , YEPAX , YEInsSales , CurrentPAX , CurrentInsSales , asofinssales/ ISNULL(NULLIF(yeinssales,0),1) as percentsales , asofpax/yepax as percentpax ,currentinssales/ISNULL(NULLIF((asofinssales/ISNULL(NULLIF(yeinssales,0),1)),0),1) as projectedinssales from q_00 as a join q_01 as b on (b.DIVISION = a.DIVISION and b.SDESCR = a.SDESCR and b.DYYYY = a.DYYYY) join q_02 as c on (b.DIVISION = c.DIVISION and b.SDESCR = c.SDESCR) order by a.DIVISION, a.SDESCR, a.DYYYY ;

    Read the article

  • Why wont my if statement work, in my stored procedure

    - by MyHeadHurts
    Alright so i am not even sure if this is possible I have a q_00 and q_01 and q_02 which are all in my stored procedure. then on the bottom i have 3 select statements that select a certain catagory for example Sales,Net Sales and INS sales What i want to be able to do is if the user types exec (name of my sp) (sales) (and a year which is the @yearparameter) it will run the sales select statement If they type Exec (name of my SP) netsales (@Yeartoget) it will show the net sales is this possible or do i need multiple stored procedures ALTER PROCEDURE [dbo].[casof] @YearToGet int, @mode VARCHAR(20) as ; with q_00 as ( select DIVISION , SDESCR , DYYYY , sum(APRICE) as asofSales , sum(PARTY) as asofPAX , sum(NetAmount) as asofNetSales , sum(InsAmount) as asofInsSales , sum(CancelRevenue) as asofCXSales , sum(OtherAmount) as asofOtherSales , sum(CXVALUE) as asofCXValue from dbo.B101BookingsDetails where Booked <= CONVERT(int,DateAdd(year, @YearToGet - Year(getdate()), DateAdd(day, DateDiff(day, 1, getdate()), 0))) and DYYYY = @YearToGet group by DIVISION, SDESCR, DYYYY ), q_01 as ( select DIVISION , SDESCR , DYYYY , sum(APRICE) as YESales , sum(PARTY) as YEPAX , sum(NetAmount) as YENetSales , sum(InsAmount) as YEInsSales , sum(CancelRevenue) as YECXSales , sum(OtherAmount) as YEOtherSales , sum(CXVALUE) as YECXValue from dbo.B101BookingsDetails where DYYYY=@YearToGet group by DIVISION, SDESCR, DYYYY ), q_02 as ( select DIVISION , SDESCR , DYYYY , sum(APRICE) as CurrentSales , sum(PARTY) as CurrentPAX , sum(NetAmount) as CurrentNetSales , sum(InsAmount) as CurrentInsSales , sum(CancelRevenue) as CurrentCXSales , sum(OtherAmount) as CurrentOtherSales , sum(CXVALUE) as CurrentCXValue from dbo.B101BookingsDetails where Booked <= CONVERT(int,DateAdd(year, (year( getdate() )) - Year(getdate()), DateAdd(day, DateDiff(day, 1, getdate()), 0))) and DYYYY = (year( getdate() )) group by DIVISION, SDESCR, DYYYY ) IF @mode = 'sales' select a.DIVISION , a.SDESCR , a.DYYYY , asofSales , asofPAX , YESales , YEPAX , CurrentSales , CurrentPAX , asofsales/ ISNULL(NULLIF(yesales,0),1) as percentsales , asofpax/yepax as percentpax ,currentsales/ISNULL(NULLIF((asofsales/ISNULL(NULLIF(yesales,0),1)),0),1) as projectedsales ,currentpax/ISNULL(NULLIF((asofpax/ISNULL(NULLIF(yepax,0),1)),0),1) as projectedpax from q_00 as a join q_01 as b on (b.DIVISION = a.DIVISION and b.SDESCR = a.SDESCR and b.DYYYY = a.DYYYY) join q_02 as c on (b.DIVISION = c.DIVISION and b.SDESCR = c.SDESCR) order by a.DIVISION, a.SDESCR, a.DYYYY ; else if @mode= 'netsales' select a.DIVISION , a.SDESCR , a.DYYYY , asofPAX , asofNetSales , YEPAX , YENetSales , CurrentPAX , CurrentNetSales , asofnetsales/ ISNULL(NULLIF(yenetsales,0),1) as percentnetsales , asofpax/yepax as percentpax ,currentnetsales/ISNULL(NULLIF((asofnetsales/ISNULL(NULLIF(yenetsales,0),1)),0),1) as projectednetsales ,currentpax/ISNULL(NULLIF((asofpax/ISNULL(NULLIF(yepax,0),1)),0),1) as projectedpax from q_00 as a join q_01 as b on (b.DIVISION = a.DIVISION and b.SDESCR = a.SDESCR and b.DYYYY = a.DYYYY) join q_02 as c on (b.DIVISION = c.DIVISION and b.SDESCR = c.SDESCR) order by a.DIVISION, a.SDESCR, a.DYYYY ; ELSE IF @mode = 'inssales' select a.DIVISION , a.SDESCR , a.DYYYY , asofPAX , asofInsSales , YEPAX , YEInsSales , CurrentPAX , CurrentInsSales , asofinssales/ ISNULL(NULLIF(yeinssales,0),1) as percentsales , asofpax/yepax as percentpax ,currentinssales/ISNULL(NULLIF((asofinssales/ISNULL(NULLIF(yeinssales,0),1)),0),1) as projectedinssales from q_00 as a join q_01 as b on (b.DIVISION = a.DIVISION and b.SDESCR = a.SDESCR and b.DYYYY = a.DYYYY) join q_02 as c on (b.DIVISION = c.DIVISION and b.SDESCR = c.SDESCR) order by a.DIVISION, a.SDESCR, a.DYYYY ;

    Read the article

  • Compiled Linq Queries with Built-in SQL functions

    - by Brandi
    I have a query that I am executing in C# that is taking way too much time: string Query = "SELECT COUNT(HISTORYID) FROM HISTORY WHERE YEAR(CREATEDATE) = YEAR(GETDATE()) "; Query += "AND MONTH(CREATEDATE) = MONTH(GETDATE()) AND DAY(CREATEDATE) = DAY(GETDATE()) AND USERID = '" + EmployeeID + "' "; Query += "AND TYPE = '5'"; I then use SqlCommand Command = new SqlCommand(Query, Connection) and SqlDataReader Reader = Command.ExecuteReader() to read in the data. This is taking over a minute to execute from C#, but is much quicker in SSMS. I see from google searching you can do something with CompiledQuery, but I'm confused whether I can still use the built in SQL functions YEAR, MONTH, DAY, and GETDATE. If anyone can show me an example of how to create and call a compiled query using the built in functions, I will be very grateful! Thanks in advance.

    Read the article

  • Store date object in sqlite database

    - by bnabilos
    Hello, I'm using a database in my Java project and I want to store date in it, the 5th and the 6th parameter are Date Object. I used the solution below but I have errors in these 2 lines : creerFilm.setDate(5, new Date (getDateDebut().getDate())); creerFilm.setDate(6, new Date (getDateFin().getDate())); PreparedStatement creerFilm = connecteur.getConnexion().prepareStatement("INSERT INTO FILM (ID, REF, NOM, DISTRIBUTEUR, DATEDEBUT, DATEFIN) VALUES (?, ?, ?, ?, ?, ?)"); creerFilm.setInt(1, getId()); creerFilm.setString(2, getReference()); creerFilm.setString(3, getNomFilm()); creerFilm.setString(4, getDistributeur()); creerFilm.setDate(5, new Date (getDateDebut().getDate())); creerFilm.setDate(6, new Date (getDateFin().getDate())); creerFilm.executeUpdate(); creerFilm.close(); Can you help me to fix that please ? Thank you

    Read the article

  • Some date math fun

    - by drsql
    Note: This concept presented is pretty simple and I am not claiming that I am the first to do this… so if you were the one who came up with this, let me know and I will give you linkage Today I was needing to get the data for the current month for a query, and it hit me that I really didn’t have a good way to do this.  There were two common methods that people use: WHERE YEAR(MonthColumn) = YEAR(Getdate()) AND MONTH(MonthColumn) = MONTH(Getdate()) But this particular method is pretty horrible...(read more)

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >