Datetime Function Glitch -- Same Settings, Different Results
Oct 23, 2006
hi guys,
i am encountering a pretty weird problem on our SQL database stored procs, particularly those concerning datetime functions. we have two setups, one is on london, and another one is here in singapore. both servers have the same regional settings, the same database tables, stored procs and functions, almost the same in every aspect. the only difference we know is that one is a direct database cut (sql 7.0), while the other used database migration in win2k.
here goes: all stored proc functions work just fine on the singapore setup. the london setup however, is not working at all! it does all the functions like change flags and status, but it doesn't update dates nor search for data by date. i have also checked on the collision names, and they are the same. where else could i start searching for discrepancies between the two?
hope to hear something from you guys, i'm getting desperate. thanks in advance!
Here's the situation: I have a ssis package which receives 3 dates as input parameters (3 datetime variables), executes different data flows and at the end inserts (among some other values) these 3 dates into a custom log table.
The problem comes while inserting the values into a log table. I added an Execute SQL Task that calls a stored procedure which inserts a record into a log table (sqlStatement exec dbo.InsertIntoLog date1=?, date2=?, date3=?). In Parameter mapping section I set parameters = variables that hold the datetime values. The problem is that the dates are inserted into the log table in American format (mm/dd/yyyy, that's the server setting), my dates are in the european format...
Any ideas how to avoid it? Is there a way to write an expression instead of the sqlStatement in which I'd do some datepart-ing?
Another tricky confusion to me is that: many algorithms settings for the native algorithms in SQL Server 2005 Data Mining do not really significantly improve the results of those mining models with settings changes? (Apart from clustering algorithm setting of cluster number, by setting 0 as the number of clusters, the system will automatically cluster the data into clusters which I assume is the best way of mining the model with this method).
Any good advcies on this will be a lot appreciated.
I am looking forward to hearing from you shortly for this confusion and thanks a lot in advance.
Found some bad behavior in the 2005 Management Studio Import and Export Wizard.
In the Select Source Tables and Views box, I selected multiple objects, and then clicked Edit Mappings.
The Transfer Settings dialog box appears, and states: "Define the settings that can be applied to all selected table transfers." I selected the "Delete rows in existing destination tables" option to overwrite the existing data. But Management Studio DID NOT DELETE THE ROWS IN THE EXISTING TABLES. Instead, the records were appended to existing data, wreaking havoc on our month-end accounting system. This happened multiple times, and occured even though the final screen confirmed that existing records would be deleted in each of the individual tables.
I'm new to handling dates in T-SQL having mainly used the more forgiving Access.
I am trying to extract the date from a 40 chr field example below - dates are dd/mm/yy
Input By Angelab On 13/08/06 19:55:33
using
SELECT CONVERT(datetime, SUBSTRING(A.Comments,22,8),3) AS EntryDate FROM (SELECT CommentDetails.Comments, InvoiceDetails.TransRef FROM (Transactions INNER JOIN CommentDetails ON Transactions.TransRef = CommentDetails.TransRef) INNER JOIN InvoiceDetails ON Transactions.TransRef = InvoiceDetails.TransRef WHERE ((Transactions.TransDate Between DATEADD(day,-5, '26-Dec-2004' ) And DATEADD(day,5, '01-Jan-2005' )) AND (SUBSTRING(CommentDetails.Comments,1,8)='Input by'))) AS A
WHERE (CONVERT(datetime, SUBSTRING(A.Comments,22,8),3) Between '26-Dec-2004' And '01-Jan-2005' )
Although without the final WHERE it works fine, so the data is OK, with the final WHERE I get "out of range datetime value", how can it be valid in the SELECT statement but not the WHERE statement.
Our SQL server is set to american dates mm/dd/yyyy.
I have a query running without issue on around 100,000 results however i have a couple where my MAX aggregate is returning two results for a MAX(date time) and i cannot figure out why. I have paired down the query to try and work it out but still don't know.
My query now looks like this (i have remove most columns)
SELECT STATUS, RunOn, sort, T_ID FROM dbo.Results WHERE (RunOn IN (SELECT MAX(RunOn) FROM dbo.Results group BY T_ID) AND T_ID = 21405)
ORDER BY sort
I added the T_ID = 21405 to restrict the results to the problematic results, if i set T_ID to any other test result i get one value based on the latest RunOn, but for some reason with this T_ID i get two values, the latest one and one slightly older... The date time looks ok, i just can't work out why the latest and one older result are returned !
The original query was grouping by more items but i removed those to try and work out what is going one, as mentioned for 99.9% of results it works perfectly, but for this one i don't know.
I am trying to pull results from an SQL Server DB into an dataset where a particular field (SMALLDATETIME) is within a particular date range. The code I was using worked fine when the database was in Access. I have made several changes already but am still getting 0 results returned when there is data that should be returned.
I was using in Access: Dim StrSQL = "SELECT ID FROM myTable WHERE myDateField>=#" & startDate & "# AND myDateField<=#" & stopDate & "# ORDER BY ID" I have changed this for SQL Server to: Dim StrSQL = "SELECT ID FROM myTable WHERE myDateField>='01/01/2003 00:00:01' AND myDateField<='01/01/2004 23:59:59' ORDER BY ID" But I am always returned 0 results even if the date range should return plenty of data. I have also tried using the BETWEEN structure with the same result.
Is there a particular format for the date I am comparing with? Am I missing something else in my query?
The connection / permissions and everything else are correct as I can read and write data to the database in numerous other pages. It is just this date comparison that is not working.
Many thanks for any help or comments you can provide.
SELECT TOP 100 PERCENT dbo._Options_Demographics.GradeLevel, dbo._Options_Demographics.Gender, dbo._Options_Demographics.Ethnicity, dbo._Options_Demographics.Age, SUM(dbo._Options_Demographics.Enrollment) AS Enrollment, dbo._Options_Demographics.OptionsYear, dbo._Options_Demographics.OptionsMonth FROM dbo._Options_Confirmed INNER JOIN dbo._Options_Demographics ON dbo._Options_Demographics.DistrictCode = dbo._Options_Confirmed.DistrictCode GROUP BY dbo._Options_Demographics.GradeLevel, dbo._Options_Demographics.Gender, dbo._Options_Demographics.Ethnicity, dbo._Options_Demographics.Age, dbo._Options_Demographics.OptionsYear, dbo._Options_Demographics.OptionsMonth ORDER BY dbo._Options_Demographics.OptionsYear, dbo._Options_Demographics.OptionsMonth, dbo._Options_Demographics.GradeLevel, dbo._Options_Demographics.Gender, dbo._Options_Demographics.Ethnicity, dbo._Options_Demographics.Age
which returns this data (the enrollment value is 4 times the correct value) grade gender eth ageenrollyearmonth 8FemaleBlack1618112003December 8FemaleBlack1716212003December 8FemaleBlack187932003December 8FemaleBlack18P2872003December
If I remove the sum function and manually add, my totals are correct ... SELECT TOP 100 PERCENT _Options_Demographics.GradeLevel, _Options_Demographics.Gender, _Options_Demographics.Ethnicity, _Options_Demographics.Age, _Options_Demographics.Enrollment, _Options_Demographics.OptionsYear, _Options_Demographics.OptionsMonth FROM _Options_Confirmed RIGHT OUTER JOIN _Options_Demographics ON _Options_Demographics.DistrictCode = _Options_Confirmed.DistrictCode GROUP BY _Options_Demographics.GradeLevel, _Options_Demographics.Gender, _Options_Demographics.Ethnicity, _Options_Demographics.Age, _Options_Demographics.Enrollment, _Options_Demographics.OptionsYear, _Options_Demographics.OptionsMonth ORDER BY _Options_Demographics.OptionsYear, _Options_Demographics.OptionsMonth, _Options_Demographics.GradeLevel, _Options_Demographics.Gender, _Options_Demographics.Ethnicity, _Options_Demographics.Age
I've been looking at this for too long and I know that is something very trivial ...
I have SQL table with dateTime field which is INT type (This field contains a number representing DATE / TIME) I would like to convert this umber to actuall date time output. However, SQL gives invalid date times. See below) Appears the resulting date time are all the same. SQL COMMAND Select TimeStamp, cast(convert(TimeStamp,103) As datetime) from winsData2 OUTPUT TimeStamp Converted TimeStamp 2147483647 1900-01-01 00:00:00.343 2147483647 1900-01-01 00:00:00.343 1178694066 1900-01-01 00:00:00.343 2147483647 1900-01-01 00:00:00.343 1178688211 1900-01-01 00:00:00.343 1178828143 1900-01-01 00:00:00.343 2147483647 1900-01-01 00:00:00.343 Any assitance appreciated.
http://www.simple-talk.com/community/blogs/philfactor/archive/2006/03/26/710.aspx i just copied the code and checked it gives sysntax error.so please how to use that function in my database,help me
I'm working on an income deferral problem and we are using IRR to end up calculating periodic income.
As an example, I have the following inputs:
Number of periods = 9 Initial Loan = 21.46 Instalment amount =15.30 Future value=0 Guess=0.1 (10%)
Using a compiled function from Visual Studio in SQL Server 2008 we get a result of 70.71656373
Using a Microsoft Access function we get NaN
Using Microsoft Excel we get NaN
Using a web calculator we get 70 (ish, the calculator rounds the numbers)
I know that the numbers are odd, some of our data is dirty so we do expect that. I was expecting the SQL process to kick out an error (therefore converting the result into 0), but it doesn't.
Hello! My group uses scalar-valued functions to denote the FTP drives on our SQL Server 2005 database servers. This allows many (over 100) import processes to refer to that function to find the flat files they need, and if the FTP drive is changed, then only the function needs to be updated, not 100 SP's.
The function is defined this way. Currently, F: is our FTP drive:
CREATE FUNCTION [dbo].[fnFTPPath] () RETURNS varchar(200) AS BEGIN
return 'f:' END
Now the question: Can a Flat File Connection Manager be used in an SSIS ETL package that refers to the output of this function, plus the FTP folder name, so we can continue updating the FTP drive name in just one place? If so, how is this done?
I would like to save only the time into the datetime field in a table. when I do this, It will save it as "1/1/1900 15:23:00" All I would like to have is the time! Is there a way to update it so that it will only save the time?
When I get result from .NET console app, I get correct answer "JungleSektor". However, when SQL Server executes this code, it gives me "NT ServiceMSSQL $ SQL2014". How to get correct result?
Hi,Say I have a table Job with columns name, date, salary . I want to getthe name ,date and salary for the date when that person earned maximumsalary. I am using something likeSELECT X.name,X.date,X.salaryFROM job XWHERE X.salary IN(SELECT MAX(Y.salary) FROM job Y where Y.name= X.name);The problem is ; if a person earns maximum salary on two dates, both ofthe dates are printed. I just want to get any one of those two rows.I triedSELECT X.name,Min(X.date),X.salaryFROM job XWHERE X.salary IN(SELECT MAX(Y.salary) FROM job Y where Y.name= X.name);but it gives error.Can anybody please suggest a solution?Regards,Aamir
I'm working with the statistical functions Stdev and Median with calculated members. The only way I can get the "correct" answer is if I have a dimension at the same granularity as the Fact table (Actually it's a degenerate dimension of the FACT table itself). Otherwise it seems that the measure I'm using with Stdev returns results that are so wildly high, I think it must be acting on the SUM of the measure; because the measure itself is a Summed one. When I try to use the coordinates in the Stdev function, it seems like it is using the wrong set of data points :
stdev( ( [Date].[Date].[Date].members, [Parameter].[Parameter].[Parameter].members ), [Measures].[Value])Â returns answers in the thousands when it should be more like 2.5
When used with a query, there would only be a single date member and a specific parameter member. The total number of fact records is between 200 and 500 with values that range between 0 and 150. This is the version that gives me answers that resemble the total sum of the [Measures].[Value].
If I add the dimension that is essentially a row number from the fact table, it gives the right answer (slowly, but that will be a different post ....
I have a UDF --------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UDF_AlphaNumeric]') and xtype in (N'FN', N'IF', N'TF')) drop function [dbo].[UDF_AlphaNumeric] GO
CREATE function UDF_AlphaNumeric (@string nvarchar(max)) returns nvarchar(max) AS -- select dbo.UDF_AlphaNumeric('a[]#b`c,;"1$%^2"£!3') begin while @@rowcount > 0 select @string = replace(@string, substring(@string, patindex('%[^0-9a-zA-Z]%', @string), 1), '') where patindex('%[^0-9a-zA-Z]%', @string) <> 0
if @string = '' select @string = null
return @string end
---------------------
After creating the function I open a new query window, put in the below two calls to the function, and run them
I'm querying a database table that creates a time stamp in seconds only. I have a starting time of 1099725928 = 11/6/2004 12:25:28 AM. So that if another entry is made 1 second later the time stamp value entered into the table is 1099725929. The front end application does the converstion from the seconds counter to the datetime format. The query I am writing calls information from this table for a different application that does not have the conversion capability. If I know the starting point (I don't want to create a conversion table) which is 1099725928 = 11/6/2004 12:25:28 AM, is it possible to write into my query script a function to convert the seconds value to the correct datetime format? It would need to accurately account for leapyear and even/odd months.
************************************************************************************************ Select Case_ID_, Region, Assigned_To_Group_, Assigned_To_Individual_, Status, Priority, Category, Type, Item, Affiliate, Hours_to_resolve, Resolved_Time, Assign_Time, Create_Time From HPD_HelpDesk Where Region = 'Central Valley' and Assigned_To_Group_ = 'CVSA Desktop Support' and Status In (1, 2, 3, 4, 5) and Priority In (0, 1, 2, 3)
Order by Case_ID_ Desc************************************************************************************************
I have a table adapter for one of my SQL2005 tables, and in two different fields I accept a date time. Now 99% of the times, new rows to this table will be filled out using DateTIme.Now(), as a Time Stamp is what I'm going for.
Here is the line of code in question...cops_current_data_adapter.Insert(ProductOrder, Convert.ToInt16(Session["StationId"].ToString()), PartNumber, DateTime.Now, DateTime.Now, Convert.ToInt16(qty), 0); The second DateTime.Now is the one that can be null, and it's throwing a formatting error everytime I try and drop it in there. It's a FormatException, and there's not much more to the example except unhelpful tips like be careful when conveting a string to a dateTime, which I'm not doing. Needless to say for the code to compile, and then throw a Format error at runtime is a bit frustraiting. Any suggestions would be most appreciated
Hi, have configured an ODBC linked server for an Adaptive Server Anywhere (ASA6.0) database. I have to write a function (not a procedure) that receives a number (@Code) and returns 1 if it was found on a table in the linked server, or 0 if not. Looks very simple... One problem, is that the queries on a linked-server must be made through the OPENQUERY statement, which doesen't support dynamic parameters. I've solved this making the whole query a string, and executing it, something like this:
SET @SQL='SELECT * FROM OPENQUERY(CAT_ASA, ''SELECT code FROM countries WHERE code=' + @Code + ''')' EXEC sp_executesql @SQL
(CAT_ASA is the linked-server's name)
Then, i would use @@ROWCOUNT to determine if the code exists or not. But before this, a problem appears: sp_executesql is not allowed within a function (only extended procedures are allowed). Does somebody know how to make what i want?? I prefer to avoid using temporary tables. Thanks!
Hey im trying to store a category name and the date into a database. For some reason i keep getting this error Implicit conversion from data type datetime to int is not allowed. Use the CONVERT function to run this query. This error is the error im getting back from the database. the datetime field in the database is a datatype (DateTime) so what exactly is going on ?protected void InsertNewCat_Click(object sender, EventArgs e) { string insertSql = "INSERT into Category (CategoryName,Date) VALUES (@Category, @Date)"; string conString = WebConfigurationManager.ConnectionStrings["ProCo"].ConnectionString; SqlConnection con = new SqlConnection(conString); SqlCommand cmd = new SqlCommand(insertSql, con); cmd.Parameters.AddWithValue("@Category", NewCat.Text); cmd.Parameters.AddWithValue("@Date",DateTime.Now);
hi, like, if i need to do delete some items with the id = 10000 then also need to update on the remaining items on the with the same idthen i will need to go through all the records to fetch the items with the same id right? so, is there something that i can use to hold those records so that i can do the delete and update just on those records and don't need to query twice? or is there a way to do that in one go ?thanks in advance!
I have four tables: Customer (CustomerId INT, CountyId INT), County (CountyId INT), Search(SearchId INT), and SearchCriteria (SearchCriteriaId INT, SearchId INT, CountyId INT, [others not related to this]).
I want to search Customer based off of the Search record, which could have multiple SearchCriteria records. However, if there aren't any SearchCriteria records with CountyId populated for a given Search, I want it to assume to get all Customer records, regardless of CountyId.
Right now, I'm doing it this way.
DECLARE @SearchId INT = 100 SELECT * FROM Customer WHERE CountyId IN ( SELECT CASE WHEN EXISTS(SELECT CountyId FROM SearchCriteria WHERE SearchId = @SearchId) THEN SearchCriteria.CountyId
[Code] .....
This works; it just seems cludgy. Is there a more elegant way to do this?
Hello. I currently have a website that has a table on one webpage. When a record is clicked, the primary key of that record is transfered in the query string to another page and fed into an sql statement. In this case its selecting a project on the first page, and displaying all the scripts for that project on another page. I also have an additional dropdownlist on the second page that i use to filter the scripts by an attribute called 'testdomain'. At present this works to an extent. When i click a project, i am navigated to the scripts page which is empty except for the dropdownlist. i then select a 'testdomain' from the dropdownlist and the page populates with scripts (formview) for the particular test domain. what i would like is for all the scripts to be displayed using the formview in the first instance when the user arrives at the second page. from there, they can then filter the scripts using the dropdownlist. My current SQL statement is as follows. SelectCommand="SELECT * FROM [TestScript] WHERE (([ProjectID] = @ProjectID) AND ([TestDomain] = @TestDomain))" So what is happening is when testdomain = a null value, it does not select any scripts. Is there a way i can achieve the behaivour of the page as i outlined above? Any help would be appreciated. Thanks, James.