Showing posts with label value. Show all posts
Showing posts with label value. Show all posts

Tuesday, March 27, 2012

Date problem with ASP.NET but not in VB.NET Winform App

Edited by SomeNewKid. Please post code between<code> and</code> tags.


Hello, I have given up after 3 hours of trying to get a DBNull.Value to be inserted into SQL 2000 DB. Below is the code that exists in an object that I use both from a VB.NET Windows application and from an ASP.NET application. (same exact compiled object dll). Has ran fine with windows application for almost a year - still does. Use the same object in my new ASP.NET application and I get a SQL Overflow error that says date must be between 1753 12 am etc etc... when trying to insert null using the code below.

This one has me stumped. The lines below where I set the date are basically this (what the logic equates to):

oDR.Item("CT_CustomDate1") = DBNull.Value
oDR.Item("CT_CustomDate2") = DBNull.Value

Error gets thrown when this line is executed:

oDA.Update(oDT)

Also, the CT_CustomDate1 & 2 fields in the SQL Server 2000 DB are of type SmallDateTime and the variables in object used in code function below are Date. I've tried every combination of Date, DateTime, SmallDateTime, etc. etc. to no avail.

Thanks for you help!

 Public Function AddNew(ByVal sGUID As String) As Boolean
'Saves all new contact information to database
Dim sSQL As String
sSQL = "SELECT * FROM Contact WHERE 1=2"
Dim oConn As New SqlConnection(sConnectionString)
Dim oDT As New DataTable
Dim oDA As New SqlDataAdapter(sSQL, oConn)
Dim oDR As DataRow
Dim bSuccess As Boolean

Try
oDA.Fill(oDT)

Dim dataCommandBuilder As New SqlCommandBuilder(oDA)
oDA.InsertCommand = dataCommandBuilder.GetInsertCommand
oDA.DeleteCommand = dataCommandBuilder.GetDeleteCommand
oDA.UpdateCommand = dataCommandBuilder.GetUpdateCommand

oDR = oDT.NewRow

oDR.Item("CT_GUID") = sGUID
oDR.Item("CT_CompanyGUID") = CTCompanyGUID
oDR.Item("CT_Prefix") = CTPrefix
oDR.Item("CT_FirstName") = CTFirstName
oDR.Item("CT_MiddleName") = CTMiddleName
oDR.Item("CT_LastName") = CTLastName
oDR.Item("CT_Suffix") = CTSuffix
oDR.Item("CT_Title") = CTTitle
oDR.Item("CT_ContactAddress") = CTContactAddress
oDR.Item("CT_Address1") = CTAddress1
oDR.Item("CT_Address2") = CTAddress2
oDR.Item("CT_City") = CTCity
oDR.Item("CT_State") = CTState
oDR.Item("CT_Zip") = CTZip
oDR.Item("CT_Country") = CTCountry
oDR.Item("CT_InternationalPhone") = CTInternationalPhone
oDR.Item("CT_Phone") = CTPhone
oDR.Item("CT_Fax") = CTFax
oDR.Item("CT_Cell") = CTCell
oDR.Item("CT_AltPhone") = CTAltPhone
oDR.Item("CT_Assistant") = CTAssistant
oDR.Item("CT_AssistantPhone") = CTAssistantPhone
oDR.Item("CT_NoEmail") = CTNoEmail
oDR.Item("CT_EmailAddress") = CTEmailAddress
oDR.Item("CT_Confidential") = CTConfidential
oDR.Item("CT_TypeGUID") = CTTypeGUID
oDR.Item("CT_Designation") = ""
oDR.Item("CT_LastUpdate") = CTLastUpdate
oDR.Item("CT_UpdatedByWho") = CTUpdatedByWho
oDR.Item("CT_Location") = CTLocation
oDR.Item("CT_CustomBit1") = CTCustomBit1
oDR.Item("CT_CustomBit2") = CTCustomBit2
oDR.Item("CT_CustomBit3") = CTCustomBit3
oDR.Item("CT_CustomBit4") = CTCustomBit4
oDR.Item("CT_CustomBit5") = CTCustomBit5
oDR.Item("CT_CustomBit6") = CTCustomBit6
oDR.Item("CT_CustomBit7") = CTCustomBit7
oDR.Item("CT_CustomStr1") = CTCustomStr1
oDR.Item("CT_CustomStr2") = CTCustomStr2
oDR.Item("CT_CustomStr3") = CTCustomStr3
oDR.Item("CT_CustomStr4") = CTCustomStr4
oDR.Item("CT_CustomStr5") = CTCustomStr5
oDR.Item("CT_CustomStr6") = CTCustomStr6
oDR.Item("CT_CustomStr7") = CTCustomStr7
oDR.Item("CT_CustomStr8") = CTCustomStr8
oDR.Item("CT_CustomStr9") = CTCustomStr9
oDR.Item("CT_CustomStr10") = CTCustomStr10
oDR.Item("CT_CustomStr11") = CTCustomStr11
oDR.Item("CT_CustomStr12") = CTCustomStr12
oDR.Item("CT_CustomStr13") = CTCustomStr13
oDR.Item("CT_CustomPhone1") = CTCustomPhone1
oDR.Item("CT_CustomPhone2") = CTCustomPhone2
oDR.Item("CT_CustomPhone3") = CTCustomPhone3
oDR.Item("CT_CustomPhone4") = CTCustomPhone4
oDR.Item("CT_CustomDate1") = IIf(CTCustomDate1 = #12:00:00 AM#, DBNull.Value, CTCustomDate1)
oDR.Item("CT_CustomDate2") = IIf(CTCustomDate2 = #12:00:00 AM#, DBNull.Value, CTCustomDate2)
'oDR.Item("CT_CustomDate1") = CDate(#1/1/1753#)
'oDR.Item("CT_CustomDate2") = CDate(#1/1/1753#)
oDR.Item("CT_CustomAmount1") = CTCustomAmount1
oDR.Item("CT_CustomAmount2") = CTCustomAmount2
oDR.Item("CT_CustomType1GUID") = CTCustomType1GUID
oDR.Item("CT_CustomType2GUID") = CTCustomType2GUID
oDR.Item("CT_CustomCompany1GUID") = IIf(CTCustomCompany1GUID = "00", DBNull.Value, CTCustomCompany1GUID)
oDR.Item("CT_CustomCompany2GUID") = IIf(CTCustomCompany2GUID = "00", DBNull.Value, CTCustomCompany2GUID)
oDR.Item("CT_CustomContact1GUID") = IIf(CTCustomContact1GUID = "00", DBNull.Value, CTCustomContact1GUID)

oDT.Rows.Add(oDR)
oDA.Update(oDT)
CTGUID = sGUID
bSuccess = True
Catch err As Exception
MsgBox("Error saving new contact..." & vbCrLf & vbCrLf & err.Message, MsgBoxStyle.Critical + MsgBoxStyle.OKOnly, "Database Error")
bSuccess = False
End Try

AddNew = bSuccess

End Function

Are you sure your ASP.NET application are referencing the same assemblies as the
WinForm?
Are they running under the same Framework version?
DataAccessApplicationBlock?

Regards
Fredriksql

Sunday, March 25, 2012

Date Picker formatting

Im sure we have all seen this error before:
"The value for the report parameter XXX is not valid for its type"

I have a report (RS 2005) that has 2 date parameters, "start" and "end".

My SQL in not very complicated at all, I have a simple WHERE date between @.start and @.end

But when I go to view the report in VS2005, I get the above error.

I am yet to find a decent fix for this, what is going on? the date I am trying is:
"26/02/2007" now, obviously its trying to us the en-US formatting, but im in Australia, so I want en-AU.

I have changed my report Language setting to be en-AU, my local settings in Region Setting is English (Australia). (BTW, I had to change the Language setting in my report through the XML, is there a better way to do this?)

How do I fix this? I have searched an searched but no-one seems to be able to give a clear answer as to what is going on....

Hi,

I think the date/time picker sends the datetime parameter to the SQL query on the server using the regional settings of the client PC, and not the server settings. Then, the server will try to interpret this date using the server Regional Options. Can you specify both Regional Options of client and Reporting Server? If what I'm saying doesn't make sense, please let me know... Because I have users with different local settings, I have not been able to use the datetime picker, because I don't know in advance in what format I will receive it in my query...

Regards, Jeroen

|||I do know what you are saying. Thanks for that, it is what I assumed. I wonder why Microsoft did it this way? Surely it should be on a report by report basis...

I did however install the SP2 for SQL 2005 last night and it seemed to fix my problem with my regional settings. Now the datepicker works like it should. But I dont know if it was simply because I had to restart my PC for the update, or not.

Who knows, but either way I am going to have to manipulate the Reporting Servers regional settings. Unless they are already correct (which I am hoping they are).

Thanks for the tips

Date Picker formatting

Im sure we have all seen this error before:
"The value for the report parameter XXX is not valid for its type"

I have a report (RS 2005) that has 2 date parameters, "start" and "end".

My SQL in not very complicated at all, I have a simple WHERE date between @.start and @.end

But when I go to view the report in VS2005, I get the above error.

I am yet to find a decent fix for this, what is going on? the date I am trying is:
"26/02/2007" now, obviously its trying to us the en-US formatting, but im in Australia, so I want en-AU.

I have changed my report Language setting to be en-AU, my local settings in Region Setting is English (Australia). (BTW, I had to change the Language setting in my report through the XML, is there a better way to do this?)

How do I fix this? I have searched an searched but no-one seems to be able to give a clear answer as to what is going on....

Hi,

I think the date/time picker sends the datetime parameter to the SQL query on the server using the regional settings of the client PC, and not the server settings. Then, the server will try to interpret this date using the server Regional Options. Can you specify both Regional Options of client and Reporting Server? If what I'm saying doesn't make sense, please let me know... Because I have users with different local settings, I have not been able to use the datetime picker, because I don't know in advance in what format I will receive it in my query...

Regards, Jeroen

|||I do know what you are saying. Thanks for that, it is what I assumed. I wonder why Microsoft did it this way? Surely it should be on a report by report basis...

I did however install the SP2 for SQL 2005 last night and it seemed to fix my problem with my regional settings. Now the datepicker works like it should. But I dont know if it was simply because I had to restart my PC for the update, or not.

Who knows, but either way I am going to have to manipulate the Reporting Servers regional settings. Unless they are already correct (which I am hoping they are).

Thanks for the tipssql

Date part of DateTime

I'm trying this simple query in SQL Server 2005:
SELECT * FROM tblRecords
WHERE InputDate = '1/30/2007'

I have two records which have value for InputDate as
1/30/2007 12:34:12
1/30/2007 11:23:32

But the query returns no records due to the time part of the date.
How do I pick only the date part for comparison and discard the time part in the InputDate ?

try this...

SELECT * FROM tblRecords
WHERE datediff(day,inputdate,'1/30/2007') = 0

|||I dont think you need to compare month and year...its redundant|||

You're right, apologies. It's been a long day. I've scrubbed my previous post.

Chris

:)

|||

A few approaches:

This trick relies on the

fact that datetime values are represented internally as floating point

values. The integer part represents the date, and the fractional part

the time. So rounding down to the nearest integer value gives you a

date.

DECLARE @.d datetime
SET @.d =

GETDATE()
SELECT @.d
SELECT CAST(FLOOR(CAST(@.d AS

float)) AS datetime)

However, doing the CAST/FLOOR

trick on a column name will probably prevent the optimizer from using

indexes on that column. This is more useful when you want to get just

the date part of GETDATE() and check it against date-only values in a

column.

In this case, you can

probably do something like this:
SELECT * FROM

tblRecords
WHERE InputDate >= '1/30/2007' AND InputDate

< '2/1/2007'

Or if you're comparing against a

variable, this would probably do the trick:
SELECT * FROM

tblRecords
WHERE InputDate >= @.idate AND InputDate

< DATEADD(dy, 1, @.idate)

|||

I prefer David's reply:

SELECT * FROM tblRecords
WHERE InputDate >= '1/30/2007' AND InputDate < '2/1/2007'

This method can take advantage of potential indexes that might be available on the inputDate column. Note that in the following mockup that David's method gets an INDEX SEEK plan whereas the plans of the queries that enclose a function around the inputDate field will use either a CLUSTERED INDEX or a TABLE SCAN:

create table dbo.tblRecords
( rid integer not null
constraint pk_tblRecords primary key,
inputDate datetime not null,
filler char (300) not null
)
go

create index inputDate on dbo.tblRecords(inputDate)
go

update statistics dbo.tblRecords
go

insert into dbo.tblRecords
select iter,
cast(cast(cast('3/15/5' as datetime) as float)
+ 730 * dbo.rand() as datetime),
'Record # ' + convert(varchar(5), iter)
from small_iterator (nolock)

go

--set showplan_text on
go

select *
from tblRecords
where inputDate >= '1/30/2007'
and inputDate < '1/31/2007'

go

--set showplan_text off
go

-- - 47 Rows Returned -

- rid inputDate filler
-- -- -
-- 4400 2007-01-30 00:08:11.790 Record # 4400
-- 10836 2007-01-30 00:27:30.883 Record # 10836
-- ...
-- 21253 2007-01-30 10:14:39.810 Record # 21253
-- 7795 2007-01-30 11:07:24.507 Record # 7795


-- StmtText
-- --
-- |--Bookmark Lookup(BOOKMARK:([Bmk1000]), OBJECT:([tempdb].[dbo].[tblRecords]) WITH PREFETCH)
-- |--Index Seek(OBJECT:([tempdb].[dbo].[tblRecords].[inputDate]), SEEK:([tblRecords].[inputDate] >= Convert([@.1]) AND [tblRecords].[inputDate] < Convert([@.2])) ORDERED FORWARD)

-- Table 'tblRecords'. Scan count 1, logical reads 165, physical reads 0, read-ahead reads 0.

SELECT * FROM tblRecords
WHERE datediff(day,inputdate,'1/30/2007') = 0

StmtText
-- -
-- |--Clustered Index Scan(OBJECT:([tempdb].[dbo].[tblRecords].[pk_tblRecords]), WHERE:(datediff(day, [tblRecords].[inputDate], 'Jan 30 2007 12:00AM')=0))

-- Table 'tblRecords'. Scan count 1, logical reads 1313, physical reads 0, read-ahead reads 0.

|||Thank you all for the help provided.
The table is already created and filled and I cant change anything in the table.
I'll use one of the above methods to get the result|||

Some

time it is required to use Convert even though it decrease the performance

SELECT * FROM tblRecords

WHERE convert(Varchar(10),InputDate,101) = '30/01/2007'

Date part of a dateTime value

Hi,
This is no function in SQL Server to get only the date part of a datetime
variable, sometime, and usually most of the time, I would like to have a
query to get the result of only some specific day's, and I am not sure what
could be the best way to do this query.
For example, if I want to get all the records of my table for only todays.
Thanks in advance for your advice on this.
FrankYou can get the Date part of the date time using the datepart function.
select Convert(nvarchar(25),getdate(),100 )
You can use the datediff function for retrieving the current day's
record
Select * from table where datediff(d,getdate(),datecolumn) = 0|||Hi,
SELECT * from YOurTable
Where Datefield >= convert(VARCHAR(8),getdate(),112)
Uses an ISO Date format, you could also Convert the Datefield Column, but
this wont need to be neccessary because of causing performance issues.
HTH, Jens Smeyer.
http://www.sqlserver2005.de
--
"Frank" <wangping@.lucent.com> schrieb im Newsbeitrag
news:%23Bu0Lt9QFHA.3868@.TK2MSFTNGP10.phx.gbl...
> Hi,
> This is no function in SQL Server to get only the date part of a datetime
> variable, sometime, and usually most of the time, I would like to have a
> query to get the result of only some specific day's, and I am not sure
> what
> could be the best way to do this query.
> For example, if I want to get all the records of my table for only todays.
> Thanks in advance for your advice on this.
> Frank
>|||Continuation to the above message from me ...
Sorry .. use this
select Convert(nvarchar(25),getdate(),101 )
you can also check books online for the different values instead of 101
for getting the required output|||Thanks, balacr,
The second datediff(d, getdate(), datecolumn) = 0 is exactly what I want.
B/R
Frank
<balacr@.gmail.com> wrote in message
news:1113806479.336151.291970@.l41g2000cwc.googlegroups.com...
> You can get the Date part of the date time using the datepart function.
> select Convert(nvarchar(25),getdate(),100 )
> You can use the datediff function for retrieving the current day's
> record
> Select * from table where datediff(d,getdate(),datecolumn) = 0
>|||Hi Frank,
"Frank" <wangping@.lucent.com> wrote in message
news:%23Bu0Lt9QFHA.3868@.TK2MSFTNGP10.phx.gbl...
> Hi,
> This is no function in SQL Server to get only the date part of a datetime
> variable, sometime, and usually most of the time, I would like to have a
> query to get the result of only some specific day's, and I am not sure
> what
> could be the best way to do this query.
> For example, if I want to get all the records of my table for only todays.
> Thanks in advance for your advice on this.
Use Northwind
/* (1) */
select * from orders
where
orderdate >= CAST(CONVERT(char(8), getdate(), 112) AS DATETIME) and
orderdate < DATEADD(day, 1, CAST(CONVERT(char(8), getdate(), 112) AS
DATETIME))
/* (2) */
select * from orders
where
day(orderdate) = day(getdate()) and
month(orderdate) = month(getdate()) and
year(orderdate) = year(getdate())
/* (3) */
Select * from orders
where
datediff(day ,getdate() , orderdate) = 0

> Frank
HTH,
Andrea|||Thanks, Jens,
I also noticed that the "where datediff()" method could causing performance
issues, since I was told that if in the "where clause", there is some
functions on the column, then even there is an index on that column, the
database query engine will not use it.
That is something like this,
select * from myTable where dateDiff(day, myDateColumn, getdate()) =0,
Then even on "myDateColumn" there is an index, the SQL Server will not use
that index.
Am I right?
B/R
Frank
"Jens Smeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote in
message news:eNqfyI%23QFHA.3704@.TK2MSFTNGP12.phx.gbl...
> Hi,
> SELECT * from YOurTable
> Where Datefield >= convert(VARCHAR(8),getdate(),112)
> Uses an ISO Date format, you could also Convert the Datefield Column, but
> this wont need to be neccessary because of causing performance issues.
>
> HTH, Jens Smeyer.
> --
> http://www.sqlserver2005.de
> --
> "Frank" <wangping@.lucent.com> schrieb im Newsbeitrag
> news:%23Bu0Lt9QFHA.3868@.TK2MSFTNGP10.phx.gbl...
datetime
todays.
>|||Yeah you are, thats why i pointed out not to do something with the column
rather than doing this "static" Conversion (because it will be only
evaluated once.)
HTH, Jens Smeyer.
http:/www.sqlserver2005.de
--
"Frank" <wangping@.lucent.com> schrieb im Newsbeitrag
news:uKcZMQ%23QFHA.2788@.TK2MSFTNGP09.phx.gbl...
> Thanks, Jens,
> I also noticed that the "where datediff()" method could causing
> performance
> issues, since I was told that if in the "where clause", there is some
> functions on the column, then even there is an index on that column, the
> database query engine will not use it.
> That is something like this,
> select * from myTable where dateDiff(day, myDateColumn, getdate()) =0,
> Then even on "myDateColumn" there is an index, the SQL Server will not use
> that index.
> Am I right?
> B/R
> Frank
> "Jens Smeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote
> in
> message news:eNqfyI%23QFHA.3704@.TK2MSFTNGP12.phx.gbl...
> datetime
> todays.
>|||Thanks, Andrea,
I would like to choose the first of your ideas, I think there maybe some
performance issues for the second and third ones.
B/R
Frank
"Andrea Benedetti" <abenedetti@.absistemi.it> wrote in message
news:%232XsyM%23QFHA.3076@.tk2msftngp13.phx.gbl...
> Hi Frank,
> "Frank" <wangping@.lucent.com> wrote in message
> news:%23Bu0Lt9QFHA.3868@.TK2MSFTNGP10.phx.gbl...
datetime
todays.
> Use Northwind
> /* (1) */
> select * from orders
> where
> orderdate >= CAST(CONVERT(char(8), getdate(), 112) AS DATETIME) and
> orderdate < DATEADD(day, 1, CAST(CONVERT(char(8), getdate(), 112) AS
> DATETIME))
> /* (2) */
> select * from orders
> where
> day(orderdate) = day(getdate()) and
> month(orderdate) = month(getdate()) and
> year(orderdate) = year(getdate())
> /* (3) */
> Select * from orders
> where
> datediff(day ,getdate() , orderdate) = 0
>
> HTH,
> Andrea
>sql

Date paramter default value

Hello all,
I have written a report that I would like to be sent to a person or
persons at the beginning of the week. There are two parameters in the
report that the users would normally type the dates. I know I can to the
previous week thing by using a stored procedure, but I would like to
know how I can, at report design time, give those parameters a default
date. I would like to try and use a non-queried value expression like:
=CDATE(dateadd("dd",-7,NOW())) for the start date and
=CDATE(dateadd("dd",-2,NOW())) for the end date
Would this be a valid approach?
Thanks,
Jeff JonesJeffrey Jones wrote:
> Hello all,
> I have written a report that I would like to be sent to a person or
> persons at the beginning of the week. There are two parameters in the
> report that the users would normally type the dates. I know I can to the
> previous week thing by using a stored procedure, but I would like to
> know how I can, at report design time, give those parameters a default
> date. I would like to try and use a non-queried value expression like:
> =CDATE(dateadd("dd",-7,NOW())) for the start date and
> =CDATE(dateadd("dd",-2,NOW())) for the end date
> Would this be a valid approach?
> Thanks,
> Jeff Jones
Okay...I was able to get the default thing to work. I used
=CDATE(MONTH(NOW()) & "/" & DatePart("d",DateAdd("d",-1,NOW())) & "/" &
YEAR(NOW())). Now I seem to be having a bit of a time problem on my
reporting server. My time seems to be set to UTC and I need it set to
US-Central time. Can anyone tell me how to do this? The server machine
time is correct, it is just the reporting server's output that is off.
Thanks,
Jeff Jones|||Take a look at the function ToLocalTime to convert from UTC. If the regional
settings (timezone) set on your reportserver differs from desired output
format you may have to specify timezone params in code.
=MyUTCDateTime.ToLocalTime()
"Jeffrey Jones" wrote:
> Jeffrey Jones wrote:
> > Hello all,
> > I have written a report that I would like to be sent to a person or
> > persons at the beginning of the week. There are two parameters in the
> > report that the users would normally type the dates. I know I can to the
> > previous week thing by using a stored procedure, but I would like to
> > know how I can, at report design time, give those parameters a default
> > date. I would like to try and use a non-queried value expression like:
> > =CDATE(dateadd("dd",-7,NOW())) for the start date and
> > =CDATE(dateadd("dd",-2,NOW())) for the end date
> > Would this be a valid approach?
> > Thanks,
> > Jeff Jones
> Okay...I was able to get the default thing to work. I used
> =CDATE(MONTH(NOW()) & "/" & DatePart("d",DateAdd("d",-1,NOW())) & "/" &
> YEAR(NOW())). Now I seem to be having a bit of a time problem on my
> reporting server. My time seems to be set to UTC and I need it set to
> US-Central time. Can anyone tell me how to do this? The server machine
> time is correct, it is just the reporting server's output that is off.
> Thanks,
> Jeff Jones
>|||I'm new in Reporting Services. Could you please tell me how to use the
ToLocalTime Method within Reporting Services.
Thanks
"Frederik" wrote:
> Take a look at the function ToLocalTime to convert from UTC. If the regional
> settings (timezone) set on your reportserver differs from desired output
> format you may have to specify timezone params in code.
> =MyUTCDateTime.ToLocalTime()
> "Jeffrey Jones" wrote:
> > Jeffrey Jones wrote:
> > > Hello all,
> > > I have written a report that I would like to be sent to a person or
> > > persons at the beginning of the week. There are two parameters in the
> > > report that the users would normally type the dates. I know I can to the
> > > previous week thing by using a stored procedure, but I would like to
> > > know how I can, at report design time, give those parameters a default
> > > date. I would like to try and use a non-queried value expression like:
> > > =CDATE(dateadd("dd",-7,NOW())) for the start date and
> > > =CDATE(dateadd("dd",-2,NOW())) for the end date
> > > Would this be a valid approach?
> > > Thanks,
> > > Jeff Jones
> > Okay...I was able to get the default thing to work. I used
> > =CDATE(MONTH(NOW()) & "/" & DatePart("d",DateAdd("d",-1,NOW())) & "/" &
> > YEAR(NOW())). Now I seem to be having a bit of a time problem on my
> > reporting server. My time seems to be set to UTC and I need it set to
> > US-Central time. Can anyone tell me how to do this? The server machine
> > time is correct, it is just the reporting server's output that is off.
> > Thanks,
> > Jeff Jones
> >

Monday, March 19, 2012

Date insert from VB.net problem

Hey there,

I'm trying to add rows to a table and pass a date value through. I use Format(Date.now, "dd MMM yyyy") however when I check in SQL Server Managment Studio it has swapped the day and month round (e.g. input of "7/9/2006" will be "9/7/2006" on the actual table. Actually the output is 2006-07-09 00:00:00:00.) I've put the full source code below.

Can anyone help with this?

Cheers,

Danny

Imports System.Data

Imports System.Data.SqlClient

Public Class Form1

Dim dtdate As Date

Dim cn As New SqlConnection("server=*********;database=********;USER ID=*********;password=*********")

Dim objCommand As New SqlCommand("", cn)

Dim ws As New wrtRefID.Service

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

dtdate = Now

AddHistory("ActivityID", 1, "AccountID", "AccountName", "ContactName", "Category", Microsoft.VisualBasic.Format(dtdate, "dd MMM yyyy"), 2, "Description", "UserName", Microsoft.VisualBasic.Format(dtdate, "dd MMM yyyy"), "CreateUser", "Notes", "LongNotes")

MessageBox.Show("DONE")

End Sub

Private Sub AddHistory(ByVal ActivityID As String, ByVal Type As Integer, ByVal AccountID As String, _

ByVal AccountName As String, ByVal ContactName As String, ByVal Category As String, ByVal StartDate As Date, _

ByVal Duration As Integer, ByVal Description As String, ByVal UserName As String, _

ByVal CreateDate As Date, ByVal CreateUser As String, ByVal Notes As String, ByVal LongNotes As String)

cn.Open()

objCommand.CommandText = "INSERT INTO HISTORY (HISTORYID, ACTIVITYID, Type, ACCOUNTID, ACCOUNTNAME, CONTACTNAME, " & _

"CATEGORY, STARTDATE, DURATION, DESCRIPTION, USERNAME, CREATEDATE, CREATEUSER, NOTES, LONGNOTES) " & _

"VALUES ('" & ws.MCS2_SLXID("HISTORY") & "', " & "'" & ActivityID & "', '" & Type & "', '" & AccountID & "', '" & AccountName & "', '" & ContactName & _

"', '" & Category & "', '" & StartDate & "', '" & Duration & "', '" & Description & "', '" & UserName & _

"', '" & CreateDate & "', '" & CreateUser & "', '" & Notes & "', '" & LongNotes & "')"

' MessageBox.Show(Format(dtdate, "dd MMM yyyy"))

TextBox1.Text = objCommand.CommandText

objCommand.ExecuteNonQuery()

cn.Close()

End Sub

End Class

Before explaining how to fix the date issue, it's important

to point out that your code may be vulnerable to a damaging

SQL injection attack. If the USER ID here has permission

to do more than insert rows into the table HISTORY, and if

you are not validating input in any way on the client side,

you are in trouble. A malicious user of your application

could enter into LongNotes, for example, a single quote

character followed by any SQL statement he or she wants to

run (like DELETE FROM HISTORY, or much worse, if this session

is opened by the sa account). See this article for more

information: www.sommarskog.se/dynamic_sql.html, or search

the web for "SQL injection."

Please, please, please, always use parameterized queries

or SQL stored procedures (and in the latter case, not

ones that just concatenate user input themselves).

You may be validating input on the client side or using

an account with limited privilege, in which case you should

at least add a comment in your code to note that this code

relies on security to be implemented elsewhere. However,

in my opinion, client-side-only security for this sort

of thing is not sufficient. Just to give one example,

some web sites will enforce what is typed into a form,

but overlook the fact that the form may not be the only

place to supply parameter values - direct specification

in the URL might be, too, and those values won't be

validated.

The best way to pass a date is through a parameterized

query or stored procedure, in which case you don't have

to use any format - you just pass it as a datetime value,

such as a SqlDateTime.

If you must pass your date as a string (and it's unlikely you

must, but it's a quicker, if more reckless, fix from what

you have now than to address the security and use parameters),

use the one date-only string format that SQL Server will

interpret consistently across culture settings: 'yyyymmdd'.

Be sure it's the string 'yyyymmdd', and not the integer yyyymmdd.

The only other safe format is the full datetime format

'YYYY-MM-DDTHH:MM:SS.mmm' (including the T character).

Vulnerable code like this is all too common, and I want

to say something whenever I see it.

Steve Kass

Drew University

http://www.stevekass.com

JediDanny@.discussions.microsoft.com wrote:

> This post has been edited either by the author or a moderator in the

> Microsoft Forums: http://forums.microsoft.com

>

> Hey there,

>

> I'm trying to add rows to a table and pass a date value through. I use

> Format(Date.now, "dd MMM yyyy") however when I check in SQL Server

> Managment Studio it has swapped the day and month round (e.g. input of

> "7/9/2006" will be "9/7/2006" on the actual table. Actually the output

> is 2006-07-09 00:00:00:00.) I've put the full source code below.

>

> Can anyone help with this?

>

> Cheers,

>

> Danny

>

>

>

> Imports System.Data

>

> Imports System.Data.SqlClient

>

> Public Class Form1

>

> Dim dtdate As Date

>

> Dim cn As New SqlConnection("server=*********;database=********;USER

> ID=*********;password=*********")

>

> Dim objCommand As New SqlCommand("", cn)

>

> Dim ws As New wrtRefID.Service

>

> Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As

> System.EventArgs) Handles Button1.Click

>

> dtdate = Now

>

> AddHistory("ActivityID", 1, "AccountID", "AccountName", "ContactName",

> "Category", Microsoft.VisualBasic.Format(dtdate, "dd MMM yyyy"), 2,

> "Description", "UserName", Microsoft.VisualBasic.Format(dtdate, "dd MMM

> yyyy"), "CreateUser", "Notes", "LongNotes")

>

> MessageBox.Show("DONE")

>

> End Sub

>

> Private Sub AddHistory(ByVal ActivityID As String, ByVal Type As

> Integer, ByVal AccountID As String, _

>

> ByVal AccountName As String, ByVal ContactName As String, ByVal Category

> As String, ByVal StartDate As Date, _

>

> ByVal Duration As Integer, ByVal Description As String, ByVal UserName

> As String, _

>

> ByVal CreateDate As Date, ByVal CreateUser As String, ByVal Notes As

> String, ByVal LongNotes As String)

>

> cn.Open()

>

> objCommand.CommandText = "INSERT INTO HISTORY (HISTORYID, ACTIVITYID,

> Type, ACCOUNTID, ACCOUNTNAME, CONTACTNAME, " & _

>

> "CATEGORY, STARTDATE, DURATION, DESCRIPTION, USERNAME, CREATEDATE,

> CREATEUSER, NOTES, LONGNOTES) " & _

>

> "VALUES ('" & ws.MCS2_SLXID("HISTORY") & "', " & "'" & ActivityID & "',

> '" & Type & "', '" & AccountID & "', '" & AccountName & "', '" &

> ContactName & _

>

> "', '" & Category & "', '" & StartDate & "', '" & Duration & "', '" &

> Description & "', '" & UserName & _

>

> "', '" & CreateDate & "', '" & CreateUser & "', '" & Notes & "', '" &

> LongNotes & "')"

>

> ' MessageBox.Show(Format(dtdate, "dd MMM yyyy"))

>

> TextBox1.Text = objCommand.CommandText

>

> objCommand.ExecuteNonQuery()

>

> cn.Close()

>

> End Sub

>

> End Class

>

>

|||

It's doing exactly what you told it to do.

Your format string is saying day + month + year (ddMMyyyy) This is not wrong. You're reading it wrong.

If you want it to say month + day + year then write the format string thataway (MMddyyyy)

Adamus

|||

NNTP User wrote:

Before explaining how to fix the date issue, it's important

to point out that your code may be vulnerable to a damaging

SQL injection attack. If the USER ID here has permission

to do more than insert rows into the table HISTORY, and if

you are not validating input in any way on the client side,

you are in trouble. A malicious user of your application

could enter into LongNotes, for example, a single quote

character followed by any SQL statement he or she wants to

run (like DELETE FROM HISTORY, or much worse, if this session

is opened by the sa account). See this article for more

information: www.sommarskog.se/dynamic_sql.html, or search

the web for "SQL injection."

Please, please, please, always use parameterized queries

or SQL stored procedures (and in the latter case, not

ones that just concatenate user input themselves).

You may be validating input on the client side or using

an account with limited privilege, in which case you should

at least add a comment in your code to note that this code

relies on security to be implemented elsewhere. However,

in my opinion, client-side-only security for this sort

of thing is not sufficient. Just to give one example,

some web sites will enforce what is typed into a form,

but overlook the fact that the form may not be the only

place to supply parameter values - direct specification

in the URL might be, too, and those values won't be

validated.

The best way to pass a date is through a parameterized

query or stored procedure, in which case you don't have

to use any format - you just pass it as a datetime value,

such as a SqlDateTime.

If you must pass your date as a string (and it's unlikely you

must, but it's a quicker, if more reckless, fix from what

you have now than to address the security and use parameters),

use the one date-only string format that SQL Server will

interpret consistently across culture settings: 'yyyymmdd'.

Be sure it's the string 'yyyymmdd', and not the integer yyyymmdd.

The only other safe format is the full datetime format

'YYYY-MM-DDTHH:MM:SS.mmm' (including the T character).

Vulnerable code like this is all too common, and I want

to say something whenever I see it.

Steve Kass

Drew University

http://www.stevekass.com

JediDanny@.discussions.microsoft.com wrote:

> This post has been edited either by the author or a moderator in the

> Microsoft Forums: http://forums.microsoft.com

>

> Hey there,

>

> I'm trying to add rows to a table and pass a date value through. I use

> Format(Date.now, "dd MMM yyyy") however when I check in SQL Server

> Managment Studio it has swapped the day and month round (e.g. input of

> "7/9/2006" will be "9/7/2006" on the actual table. Actually the output

> is 2006-07-09 00:00:00:00.) I've put the full source code below.

>

> Can anyone help with this?

>

> Cheers,

>

> Danny

>

>

>

> Imports System.Data

>

> Imports System.Data.SqlClient

>

> Public Class Form1

>

> Dim dtdate As Date

>

> Dim cn As New SqlConnection("server=*********;database=********;USER

> ID=*********;password=*********")

>

> Dim objCommand As New SqlCommand("", cn)

>

> Dim ws As New wrtRefID.Service

>

> Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As

> System.EventArgs) Handles Button1.Click

>

> dtdate = Now

>

> AddHistory("ActivityID", 1, "AccountID", "AccountName", "ContactName",

> "Category", Microsoft.VisualBasic.Format(dtdate, "dd MMM yyyy"), 2,

> "Description", "UserName", Microsoft.VisualBasic.Format(dtdate, "dd MMM

> yyyy"), "CreateUser", "Notes", "LongNotes")

>

> MessageBox.Show("DONE")

>

> End Sub

>

> Private Sub AddHistory(ByVal ActivityID As String, ByVal Type As

> Integer, ByVal AccountID As String, _

>

> ByVal AccountName As String, ByVal ContactName As String, ByVal Category

> As String, ByVal StartDate As Date, _

>

> ByVal Duration As Integer, ByVal Description As String, ByVal UserName

> As String, _

>

> ByVal CreateDate As Date, ByVal CreateUser As String, ByVal Notes As

> String, ByVal LongNotes As String)

>

> cn.Open()

>

> objCommand.CommandText = "INSERT INTO HISTORY (HISTORYID, ACTIVITYID,

> Type, ACCOUNTID, ACCOUNTNAME, CONTACTNAME, " & _

>

> "CATEGORY, STARTDATE, DURATION, DESCRIPTION, USERNAME, CREATEDATE,

> CREATEUSER, NOTES, LONGNOTES) " & _

>

> "VALUES ('" & ws.MCS2_SLXID("HISTORY") & "', " & "'" & ActivityID & "',

> '" & Type & "', '" & AccountID & "', '" & AccountName & "', '" &

> ContactName & _

>

> "', '" & Category & "', '" & StartDate & "', '" & Duration & "', '" &

> Description & "', '" & UserName & _

>

> "', '" & CreateDate & "', '" & CreateUser & "', '" & Notes & "', '" &

> LongNotes & "')"

>

> ' MessageBox.Show(Format(dtdate, "dd MMM yyyy"))

>

> TextBox1.Text = objCommand.CommandText

>

> objCommand.ExecuteNonQuery()

>

> cn.Close()

>

> End Sub

>

> End Class

>

>

WTF? lol|||

NNTP User wrote:

Before explaining how to fix the date issue, it's important

to point out that your code may be vulnerable to a damaging

SQL injection attack. If the USER ID here has permission

to do more than insert rows into the table HISTORY, and if

you are not validating input in any way on the client side,

you are in trouble. A malicious user of your application

could enter into LongNotes, for example, a single quote

character followed by any SQL statement he or she wants to

run (like DELETE FROM HISTORY, or much worse, if this session

is opened by the sa account). See this article for more

information: www.sommarskog.se/dynamic_sql.html, or search

the web for "SQL injection."

Please, please, please, always use parameterized queries

or SQL stored procedures (and in the latter case, not

ones that just concatenate user input themselves).

You may be validating input on the client side or using

an account with limited privilege, in which case you should

at least add a comment in your code to note that this code

relies on security to be implemented elsewhere. However,

in my opinion, client-side-only security for this sort

of thing is not sufficient. Just to give one example,

some web sites will enforce what is typed into a form,

but overlook the fact that the form may not be the only

place to supply parameter values - direct specification

in the URL might be, too, and those values won't be

validated.

The best way to pass a date is through a parameterized

query or stored procedure, in which case you don't have

to use any format - you just pass it as a datetime value,

such as a SqlDateTime.

If you must pass your date as a string (and it's unlikely you

must, but it's a quicker, if more reckless, fix from what

you have now than to address the security and use parameters),

use the one date-only string format that SQL Server will

interpret consistently across culture settings: 'yyyymmdd'.

Be sure it's the string 'yyyymmdd', and not the integer yyyymmdd.

The only other safe format is the full datetime format

'YYYY-MM-DDTHH:MM:SS.mmm' (including the T character).

Vulnerable code like this is all too common, and I want

to say something whenever I see it.

Steve Kass

Drew University

http://www.stevekass.com

JediDanny@.discussions.microsoft.com wrote:

> This post has been edited either by the author or a moderator in the

> Microsoft Forums: http://forums.microsoft.com

>

> Hey there,

>

> I'm trying to add rows to a table and pass a date value through. I use

> Format(Date.now, "dd MMM yyyy") however when I check in SQL Server

> Managment Studio it has swapped the day and month round (e.g. input of

> "7/9/2006" will be "9/7/2006" on the actual table. Actually the output

> is 2006-07-09 00:00:00:00.) I've put the full source code below.

>

> Can anyone help with this?

>

> Cheers,

>

> Danny

>

>

>

> Imports System.Data

>

> Imports System.Data.SqlClient

>

> Public Class Form1

>

> Dim dtdate As Date

>

> Dim cn As New SqlConnection("server=*********;database=********;USER

> ID=*********;password=*********")

>

> Dim objCommand As New SqlCommand("", cn)

>

> Dim ws As New wrtRefID.Service

>

> Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As

> System.EventArgs) Handles Button1.Click

>

> dtdate = Now

>

> AddHistory("ActivityID", 1, "AccountID", "AccountName", "ContactName",

> "Category", Microsoft.VisualBasic.Format(dtdate, "dd MMM yyyy"), 2,

> "Description", "UserName", Microsoft.VisualBasic.Format(dtdate, "dd MMM

> yyyy"), "CreateUser", "Notes", "LongNotes")

>

> MessageBox.Show("DONE")

>

> End Sub

>

> Private Sub AddHistory(ByVal ActivityID As String, ByVal Type As

> Integer, ByVal AccountID As String, _

>

> ByVal AccountName As String, ByVal ContactName As String, ByVal Category

> As String, ByVal StartDate As Date, _

>

> ByVal Duration As Integer, ByVal Description As String, ByVal UserName

> As String, _

>

> ByVal CreateDate As Date, ByVal CreateUser As String, ByVal Notes As

> String, ByVal LongNotes As String)

>

> cn.Open()

>

> objCommand.CommandText = "INSERT INTO HISTORY (HISTORYID, ACTIVITYID,

> Type, ACCOUNTID, ACCOUNTNAME, CONTACTNAME, " & _

>

> "CATEGORY, STARTDATE, DURATION, DESCRIPTION, USERNAME, CREATEDATE,

> CREATEUSER, NOTES, LONGNOTES) " & _

>

> "VALUES ('" & ws.MCS2_SLXID("HISTORY") & "', " & "'" & ActivityID & "',

> '" & Type & "', '" & AccountID & "', '" & AccountName & "', '" &

> ContactName & _

>

> "', '" & Category & "', '" & StartDate & "', '" & Duration & "', '" &

> Description & "', '" & UserName & _

>

> "', '" & CreateDate & "', '" & CreateUser & "', '" & Notes & "', '" &

> LongNotes & "')"

>

> ' MessageBox.Show(Format(dtdate, "dd MMM yyyy"))

>

> TextBox1.Text = objCommand.CommandText

>

> objCommand.ExecuteNonQuery()

>

> cn.Close()

>

> End Sub

>

> End Class

>

>

Gotta lay off the crackpipe Steve.

Sunday, March 11, 2012

Date Formatting

I know this has probably been beaten to death, but I still have not found a
way to use datetime in a matrix. I have a timestamp field with the value of
datetime.
I want to group by the date, not using the time. When I format the date, it
still groups by the datetime, not the date only. I also tried to
concatenate the date parts, but 11/10 comes right after 11/1.
Any ideas?
Thanks.You can always use function calls to generate numbers from the DateTime
value. For instance, you can use this function for the grouping (and achieve
correct date ordering):
=Year(Fields!Date.Value) * 10000 + Month(Fields!Date.Value) * 100 +
Day(Fields!Date.Value)
MSDN references:
* http://msdn.microsoft.com/library/en-us/vblr7/html/vafctday.asp
* http://msdn.microsoft.com/library/en-us/vblr7/html/vafctmonth.asp
* http://msdn.microsoft.com/library/en-us/vblr7/html/vafctyear.asp
--
This posting is provided "AS IS" with no warranties, and confers no rights.
"John Geddes" <john_g@.alamode.com> wrote in message
news:e2OV1FV4EHA.2568@.TK2MSFTNGP11.phx.gbl...
> I know this has probably been beaten to death, but I still have not found
a
> way to use datetime in a matrix. I have a timestamp field with the value
of
> datetime.
> I want to group by the date, not using the time. When I format the date,
it
> still groups by the datetime, not the date only. I also tried to
> concatenate the date parts, but 11/10 comes right after 11/1.
> Any ideas?
> Thanks.
>|||That worked pefectly. thanks!!!!
"Robert Bruckner [MSFT]" <robruc@.online.microsoft.com> wrote in message
news:OwI$$MV4EHA.3388@.TK2MSFTNGP15.phx.gbl...
> You can always use function calls to generate numbers from the DateTime
> value. For instance, you can use this function for the grouping (and
achieve
> correct date ordering):
> =Year(Fields!Date.Value) * 10000 + Month(Fields!Date.Value) * 100 +
> Day(Fields!Date.Value)
> MSDN references:
> * http://msdn.microsoft.com/library/en-us/vblr7/html/vafctday.asp
> * http://msdn.microsoft.com/library/en-us/vblr7/html/vafctmonth.asp
> * http://msdn.microsoft.com/library/en-us/vblr7/html/vafctyear.asp
> --
> This posting is provided "AS IS" with no warranties, and confers no
rights.
>
> "John Geddes" <john_g@.alamode.com> wrote in message
> news:e2OV1FV4EHA.2568@.TK2MSFTNGP11.phx.gbl...
> > I know this has probably been beaten to death, but I still have not
found
> a
> > way to use datetime in a matrix. I have a timestamp field with the
value
> of
> > datetime.
> >
> > I want to group by the date, not using the time. When I format the
date,
> it
> > still groups by the datetime, not the date only. I also tried to
> > concatenate the date parts, but 11/10 comes right after 11/1.
> >
> > Any ideas?
> >
> > Thanks.
> >
> >
>

Thursday, March 8, 2012

Date Format Problem

i have change my field like that format

= format(Fields!TimeStart.Value, "dd -MMM- yyyy")

Its working perfectly.Once i deployed my report this format is not working

once deploy my report its showing that field fill dd -MMM- yyyy why?there is no date in that field?

i dont understand can anybody know this one.

From the description it sounds like the TimeStart field is of type DateTime when running in preview (running based on the cached data from the .rdl.data file), but of type string when running on the report server when running against live data.

Are you running against the same data source in your design environment and the server?

Did you click the little green refresh icon in the preview toolbar (this will update the cached .rdl.data file kept by report designer)?

-- Robert

|||

thanx for your reply

its giving same problem.Its actually live data.Its giving once deploy my report only.

Date format of 0000-00-00 or 00:00:00

I am converting a MySQL database to SQL server 2000. I noticed that in one of the database fields in a table, they set a default value for the field as 0000-00-00. Is this okay for a default value for SQL Server 2005 ? How about a default value of 00:00:00 ?

Will

'00:00:00' is ok, while '0000-00-00' is invalid. A quick test in SQL Server:

create table testDate (id int,t smalldatetime default '00:00:00')

insert into testDate(id) select 1


create table testDate1 (id int,t smalldatetime default '0000-00-00')

insert into testDate1(id) select 1

The 2nd insert will fail because '0000-00-00' is a date out of range. In SQL, there are some instructions when using datatime and smalldatetime data type, please refer to:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_da-db_9xut.asp

Wednesday, March 7, 2012

date format according to regional setting

hi all,

is it possible to format a datetime value in report to display according to the shortdate format set in pc's regional setting ?

i manage to get the parameters to display according to the format in regional setting but is it possible for fields in report to follow shortdate format ?

btw, i can't seem to find the setting for report language under report tab in vs.

i could find language under Tools -> Options -> International Settings -> Language. is it the same thing? cos i've been reading other related posts and seems like the setting can be found under report tab..

Thanks!

Yes, you can specify the format and language style property in the report in order to do that. For detailed information about setting the language property, you can take a look at this page http://msdn2.microsoft.com/en-us/library/ms156493(SQL.90).aspx

|||

hi Fang,

thanks a lot for the swift answer. thanks a lot for pointing me to the url. had been searching high and low through the help file.

i have another problem i.e. i use stored procedure for some of the datasets and the dateformat will cause an error. i know there's a set language function for stored proc but how can i retrieve the pc's regional setting and specify it in the stored proc ?

thanks again!

|||You can pass in User!Language as a query parameter to the stored proc.|||

hi Fang,

i've tried but got this error in RS:

SET LANGUAGE failed because 'en-GB' is not an official language name or a language alias on this SQL Server.

is it the configuration in regional setting?

thanks!

Date format - Parameter/Field

Hi,

I have some difficulties to format a Date value in my reporting service.

As you know you can use this kind of expression:

=DateTime.Parse(Parameters!ReportingDate.Value).ToString("dd/MM/yyyy")

But it does not work, and when I just want to use the format property of the textbox content such as "dd/MM/yyyy", it displays "dd/MM/yyyy", not the real formatted data, this property works for "=Today()" but not for parameters and fields. What is the diffrence?

Have you an idea to format a Parameter/Field of Date type such as dd/MM/yyyy?

Many thanks!

Vin,

You can make your parameter of data type DateTime, this would eliminate the need to parse a string. If not, try

Format(CDate(Parameters!Report_Parameter_0.Value),"d")

Ham

|||

With your code, I get this error:

Cast from string "20061222" to type 'Date' is not valid.

Strange because the string has a correct date format :S

|||

Vin,

What's your Parameter data type?

Ham

|||

Also,

the value that is stored in this parameter.

Ham

|||

The parameter is an integer, it s the reason why I m using now:

=DateTime.Parse(Parameters!ReportingDate.Value.ToString())

The problem is the value of ReportingDate is "20061222" and to work as DateTime you have to have "2006/12/22", after you can display it as you want with ToString function.

I would like to have this format 2006/12/22 with / in fact, but properly...

|||

Vins,

That's a tough one, if you're using integer data type for Datetime. I guess my approach would be to change to integer into a string value

LEFT(Parameters!ReportingDate.Value.ToString,4) & "/" & Mid(Parameters!ReportingDate.Value.ToString,5,2) & "/" & RIGHT(Fields!SSN.Value,2)

The catch here is that you'll have to return always 4 digit years, 2 digit months and 2 digit days, instead of 2007/1/1 you would need 2007/01/01

Ham

|||Thanks Ham, it s working very well ;-)

Saturday, February 25, 2012

date format

The date is stored in my DB as a numeric 9(18,9) data type .How can i convert that value into regular data type
HEre are the two dates in my DB.How can i change this into regular data formart.
37774.98856
37728.38941
Thanks.What is it suppose to be?

How about

SELECT CONVERT(datetime,37774.98856)

Friday, February 24, 2012

date default parameter

Hello,

I have a date Start and End parameters. I want to set default value as previous quarters start and end date, how can I do this?

Thanks,

When you are passing the parameters to the report put the values there like
in reportpath = /<RerportDir>/ReportName&startdate=01/01/2005&enddate=01/03/2005
Hope this will solve U'r problem|||

hi JIM.H

Create a start & end date parameter and paste this code in the SRS code page and pass it today's date or a date entered by the user. This will return the Qtr's as I can understand from u'r question

PublicFunction parmQTRStartDate(ByVal currentDateAs DateTime)As System.DateTime

Dim iCurrentMonthAsInteger

' mm/dd/yyyy is format

iCurrentMonth = currentDate.Month()

SelectCase iCurrentMonth' Evaluate Number.

Case 1To 3' in First Quater return Previous Year

Return System.Convert.ToDateTime("09/01/" & currentDate.AddYears(-1).Year.ToString())

Case 4To 6' Second Quater in Return 1 Qtr

Return System.Convert.ToDateTime("01/01/" & currentDate.Year.ToString())

Case 7To 9' Third Quater in Return 2 Qtr

Return System.Convert.ToDateTime("04/01/" & currentDate.Year.ToString())

Case 10To 12' Fourth Quater in Return 3 Qtr

Return System.Convert.ToDateTime("07/01/" & currentDate.Year.ToString())

EndSelect

EndFunction

PublicFunction parmQTREndDate(ByVal currentDateAs DateTime)As System.DateTime

' mm/dd/yyyy is format

Dim iCurrentMonthAsInteger

iCurrentMonth = currentDate.Month()

SelectCase iCurrentMonth' Evaluate Number.

Case 1To 3' in First Quater return Previous Year

Return System.Convert.ToDateTime("12/31/" & currentDate.AddYears(-1).Year.ToString())

Case 4To 6' Second Quater in Return 1 Qtr

Return System.Convert.ToDateTime("03/31/" & currentDate.Year.ToString())

Case 7To 9' Third Quater in Return 2 Qtr

Return System.Convert.ToDateTime("06/30/" & currentDate.Year.ToString())

Case 10To 12' Fourth Quater in Return 3 Qtr

Return System.Convert.ToDateTime("09/30/" & currentDate.Year.ToString())

EndSelect

EndFunction
,Cheers
l0n3i200n

Sunday, February 19, 2012

Date creation in SQL

Hi,
I have a parameter that is being input as a String via Crystal Reports.
It's called 'School Year'
and a typical value is '2006'. I need to be able to create a 'Date'
that is compared to a field value in a where clause. In this case the
db field is called 'requisition_time_stamp' in the T_ORDER table. The
'requistion_time_stamp' file is of type 'datetime'.

Below is pseudo_code for what I need to do:

T_ORDER.requisition_time_stamp >= Date(ToNumber(School Year),6,1)
AND
T_ORDER.requisition_time_stamp < Date(ToNumber(School Year + 1) , 6,
1)

The 'Date' method is a mock-up and is problematic because the 'School
Year' field needs to be converted to a number so it can be incremented
in the second statement, so I also need a conversion method, something
like 'ToNumber(School Year)' .

I've looked at the Date functions in the Sybase documentation and I
don't see anything that fits what I'm trying to do.

Any help would be greatly appreciated!wgblackmon@.yahoo.com (wgblackmon@.yahoo.com) writes:
> I have a parameter that is being input as a String via Crystal Reports.
> It's called 'School Year'
> and a typical value is '2006'. I need to be able to create a 'Date'
> that is compared to a field value in a where clause. In this case the
> db field is called 'requisition_time_stamp' in the T_ORDER table. The
> 'requistion_time_stamp' file is of type 'datetime'.
> Below is pseudo_code for what I need to do:
> T_ORDER.requisition_time_stamp >= Date(ToNumber(School Year),6,1)
> AND
> T_ORDER.requisition_time_stamp < Date(ToNumber(School Year + 1) , 6,
> 1)

It's as simple as:

T_ORDER.requisition_time_stamp >= @.year + '0101'
T_ORDER.requisition_time_stamp < dateadd(DAY, 1, @.year + '1231')

YYYYMMDD is one of the few date formats that are always interpreted
the same in SQL Server.

> I've looked at the Date functions in the Sybase documentation and I
> don't see anything that fits what I'm trying to do.

Sybase? This newsgroup is for Microsoft SQL Server. Thankfully, the
solution above works for Sybase as well.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||--BEGIN PGP SIGNED MESSAGE--
Hash: SHA1

You could do something like this (in a stored procedure):

-- the INPUT parameter would be

@.school_year CHAR(4)

-- then use this in the WHERE clause

ORDER.requisition_time_stamp >= @.school_year + '0601'
AND ORDER.requisition_time_stamp < CAST(CAST(@.school_year as int)+1 as
char(4)) + '0601'

--
MGFoster:::mgf00 <at> earthlink <decimal-point> net
Oakland, CA (USA)

--BEGIN PGP SIGNATURE--
Version: PGP for Personal Privacy 5.0
Charset: noconv

iQA/AwUBRFkvk4echKqOuFEgEQJROwCfRjD+rzabv+WXmUD22z4RtR czyy4An1eh
sCSLmD3GVmLEk9RTEtCoPQo3
=TuKz
--END PGP SIGNATURE--

wgblackmon@.yahoo.com wrote:
> Hi,
> I have a parameter that is being input as a String via Crystal Reports.
> It's called 'School Year'
> and a typical value is '2006'. I need to be able to create a 'Date'
> that is compared to a field value in a where clause. In this case the
> db field is called 'requisition_time_stamp' in the T_ORDER table. The
> 'requistion_time_stamp' file is of type 'datetime'.
> Below is pseudo_code for what I need to do:
> T_ORDER.requisition_time_stamp >= Date(ToNumber(School Year),6,1)
> AND
> T_ORDER.requisition_time_stamp < Date(ToNumber(School Year + 1) , 6,
> 1)
> The 'Date' method is a mock-up and is problematic because the 'School
> Year' field needs to be converted to a number so it can be incremented
> in the second statement, so I also need a conversion method, something
> like 'ToNumber(School Year)' .
> I've looked at the Date functions in the Sybase documentation and I
> don't see anything that fits what I'm trying to do.
> Any help would be greatly appreciated!

Date created defualt value

in my database i have a "datecreated" feild, its datatype is "datetime", is it possible to set the defualt value as the time now? if so what do I put in the defualt value property? thanks a million si!

Under design view for the Table, you can set he default value of "Getdate()" (without the quotes). You dont need to do anything from yout T-SQL or application. The value is automatically inserted by SQL Server.

|||

thanks a million! thats going to save sometimeBig Smile si!

Date Conversion

I am having trouble with a simple date conversion in a table. I have
a field that is stored in a legacy system as a text value. When I
bring the data into reporting services I need to convert it to a date,
however, some records have invalid date formats, which cannot be
converted. I tried to solve the problem using the following
expression, but I still get the dreaded "#Error" in the fields that
cannot be converted to date.
=IIF((Isdate(CDate(Fields!AVACCD.Value)))=True,CDate(Fields!
ABACCD.Value),nothing)Perhaps you could use regular expressions such as:
System.Text.RegularExpressions.Regex.IsMatch(StartDate,
"(((0[1-9]|[1-9])|1[012])[- /.]((0[1-9]|[1-9])|[12][0-9]|3[01])[-
/.](19|20)\d\d)|((January|February|March|April|May|June|July|August|September|October|November|December)(\s)((0[1-9]|[1-9])|[12][0-9]|3[01])(,\s)(19|20)\d\d)|((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)(\s)((0[1-9]|[1-9])|[12][0-9]|3[01])(,\s)(19|20)\d\d)")
This returns false if the format is incorrect
"repettry@.fcbinc.com" wrote:
> I am having trouble with a simple date conversion in a table. I have
> a field that is stored in a legacy system as a text value. When I
> bring the data into reporting services I need to convert it to a date,
> however, some records have invalid date formats, which cannot be
> converted. I tried to solve the problem using the following
> expression, but I still get the dreaded "#Error" in the fields that
> cannot be converted to date.
> =IIF((Isdate(CDate(Fields!AVACCD.Value)))=True,CDate(Fields!
> ABACCD.Value),nothing)
>|||On Apr 11, 10:32 pm, repet...@.fcbinc.com wrote:
> I am having trouble with a simple date conversion in a table. I have
> a field that is stored in a legacy system as a text value. When I
> bring the data into reporting services I need to convert it to a date,
> however, some records have invalid date formats, which cannot be
> converted. I tried to solve the problem using the following
> expression, but I still get the dreaded "#Error" in the fields that
> cannot be converted to date.
> =IIF((Isdate(CDate(Fields!AVACCD.Value)))=True,CDate(Fields!
> ABACCD.Value),nothing)
You're probably going to need to use custom code to do what you're
attempting to do with the IIF. Since IIF is a function call, the
entire statement is evaluated at run time so it's throwing the error
simply because it's seeing the invalid date value in the statement.
Something like this should work:
Public function ConvertDate (exp1)
If IsDate(exp1) = False Then
ConvertDate = Nothing
Else ConvertDate = CDate(exp1)
End If
End function
Then insert
=code.ConvertDate(Fields!AVACCD.Value)
in the appropriate text box.|||On Apr 13, 1:53 pm, "toolman" <t...@.infocision.com> wrote:
> On Apr 11, 10:32 pm, repet...@.fcbinc.com wrote:
> > I am having trouble with a simple date conversion in a table. I have
> > a field that is stored in a legacy system as a text value. When I
> > bring the data into reporting services I need to convert it to a date,
> > however, some records have invalid date formats, which cannot be
> > converted. I tried to solve the problem using the following
> > expression, but I still get the dreaded "#Error" in the fields that
> > cannot be converted to date.
> > =IIF((Isdate(CDate(Fields!AVACCD.Value)))=True,CDate(Fields!
> > ABACCD.Value),nothing)
> You're probably going to need to use custom code to do what you're
> attempting to do with the IIF. Since IIF is a function call, the
> entire statement is evaluated at run time so it's throwing the error
> simply because it's seeing the invalid date value in the statement.
> Something like this should work:
> Public function ConvertDate (exp1)
> If IsDate(exp1) = False Then
> ConvertDate = Nothing
> Else ConvertDate = CDate(exp1)
> End If
> End function
> Then insert
> =code.ConvertDate(Fields!AVACCD.Value)
> in the appropriate text box.
Thanks. The custom code worked great! I used the same concept to
convert numbers as well.

Date Conversion

I'm searching on a smalldatetime field in SQL Server so a typical value would be 09/21/2005 11:30:00 AM. I have a search form which offers the user a textbox to search by date and unless they enter the exact date and time, no matching records are found. Of course I want I all records for a given day to be returned. This is how I'm doing it now. Thanks.

Dim dteDate_RequestedAsString = txtDate_Requested.Text

If dteDate_Requested <>""Then
strSqlText +=" Date_Requested='" & dteDate_Requested &"'"
EndIf

You have to change to DateTime to get the results you want because SmallDateTime have limited resolution. Try the link below for more info. Hope this helps.
http://www.stanford.edu/~bsuter/sql-datecomputations.html|||I've changed my SQL Server field type from SmallDateTime to DateTime and it's still not working. If I do a response.write on the SQL statement, I see that it's working correctly (WHERE Date_Requested='09/22/2005')|||You need to keep in mind that there is no Date data type. All ofthe data types involving dates also includes times. You need towind up with a query that looks like this:
WHERE Date_Requested >= '20050922' AND Date_Requested < '20050923'

That is my best recommendation. That will return you all recordswhere Date_Requested falls on 9/22/2005 regardless of the time part ofthe date you are storing.
I must strongly recommend to you that you use Parameters instead of concatenating UI-supplied data to a string to be executed.
Here's the why:
Please, please, please, learn about injection attacks!
How To: Protect From SQL Injection in ASP.NET

And here's the how:
Using Parameterized Query in ASP.NET, Part 1
Using Parameterized Query in ASP.NET, Part 2
|||I see. I've been a developer quite awhile and did not know this was the best way to search date fields.
This is for a small intranet app so I'm not concerned about SQL injection attacks in this case but that is very good advice.
Thanks for the help.
|||

evanburen wrote:

I see. I've been a developer quite awhile anddid not know this was the best way to search date fields.


It's just what I've learned through trial and error and seeing otherpeople struggling with it. The method I suggested will takeadvantage of any index on your date field, and it takes the time partof the date out of the equation.

evanburen wrote:

This isfor a small intranet app so I'm not concerned about SQL injectionattacks in this case but that is very good advice.


I have a few thoughts to offer on this viewpoint.
While one would like to think that all coworkers are trustworthy,a curious or disgruntled employee, or perhaps a temporary contractor,might try to access data to which they are not otherwise privileged, orperhaps even attempt to inflict damage to the database ornetwork. There still might be data which needs to be keptsafeguarded, such as payroll information, benefit information.

Friday, February 17, 2012

date conversion

hi friends,
I want to convert datetime to date.
example
select dt from abc where dt between @.dt1 and @.dt2
dt holds the value '2004-08-02 12:12:28.000'
i want dt to eliminame time before checking.
thanks
vanithaVanitha
You can use
select dt from abc where dt >=@.dt1 and dt< dateadd(day,1,@.dt2) ( It gives an
ability to use an index on dt column)
Lookup CONVERT function in the BOL
"Vanitha" <Vanitha@.discussions.microsoft.com> wrote in message
news:A2648D8E-CCD2-45DF-91AB-5DC852203A2C@.microsoft.com...
> hi friends,
> I want to convert datetime to date.
> example
> select dt from abc where dt between @.dt1 and @.dt2
> dt holds the value '2004-08-02 12:12:28.000'
> i want dt to eliminame time before checking.
> thanks
> vanitha
>|||SELECT CONVERT(DATETIME,(CONVERT(VARCHAR(12), Getdate(),7)))
"Vanitha" wrote:

> hi friends,
> I want to convert datetime to date.
> example
> select dt from abc where dt between @.dt1 and @.dt2
> dt holds the value '2004-08-02 12:12:28.000'
> i want dt to eliminame time before checking.
> thanks
> vanitha
>|||> SELECT CONVERT(DATETIME,(CONVERT(VARCHAR(12), Getdate(),7)))
This will fail if you have certain regional settings, e.g. SET LANGUAGE
RUSSIAN
Much safer to use ISO standard date formats, like YYYYMMDD; in this specific
case, better to use a real datetime instead of relying on string formatting,
then you can use an index (which is ideal for this type of query).
DECLARE @.dt SMALLDATETIME
SET @.dt = DATEADD(DAY, 0, DATEDIFF(DAY, 0, GETDATE()))
SELECT ...
WHERE dt >= @.dt AND dt < @.dt+1

Tuesday, February 14, 2012

Date and Time Parameter:

I have a report that I will use a DateCreated value for the date and time
parameters. The time stamp for the DateCreated value does carry dates and
times. This report is for three 12 hour shifts and the hours run from 7:00
PM to 7:00 AM. I need to set my default parameters to display as yesterday's
date with the time of 7:00 PM and today's with the time of 7:00 AM. How do I
write this in my sql and set my defaul parameters? Please help! Thanks,
Deborah
--
Message posted via SQLMonster.com
http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server-reporting/200604/1Well you could base your paramter on a stored procedure which returns
yesterdays date.
"Deborah via SQLMonster.com" wrote:
> I have a report that I will use a DateCreated value for the date and time
> parameters. The time stamp for the DateCreated value does carry dates and
> times. This report is for three 12 hour shifts and the hours run from 7:00
> PM to 7:00 AM. I need to set my default parameters to display as yesterday's
> date with the time of 7:00 PM and today's with the time of 7:00 AM. How do I
> write this in my sql and set my defaul parameters? Please help! Thanks,
> Deborah
> --
> Message posted via SQLMonster.com
> http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server-reporting/200604/1
>