Convert DT.Rows(0).item to DateTime String MM/dd/YYYY - sql-server

Hi i am pulling the date from sql server which returns this: 12/19/2014 4:17:31 PM
However I only want it to return 12/19/2014
I am using this to get the order date: txtOrderDate.Text = dt.Rows(0).Item("OrderDate")
How do I convert this to only return the date in this format MM/dd/YYYY?
I cannot do it using the SQL Statement because I am pulling other columns as well.
Thanks

You could get the output desidered with
Dim dt as DateTime
if Not dt.Rows(0).IsNull("OrderDate") _
AndAlso DateTime.TryParse(dt.Rows(0).Item("OrderDate"), _
CultureInfo.InvariantCulture, _
DateTimeStyles.None, dt) Then
txtOrderDate.Text = dt.ToString("MM/dd/yyyy")
else
.... ' Something to do in case of null or invalid date
End If
The use of DataRow.IsNull and DateTime.TryParse is a precautionary step to avoid any possible exception in case your column "OrderDate" is null or not in a correct format.

I think this will work:
txtOrderDate.Text = dt.Rows(0).Item("OrderDate").ToString("MM/dd/yyyy")
However, it's been a while since I've had to work with DataTable cells directly; there's a chance the above code will only have the Object type, rather than the VB.Net DateTime type, and therefore that .ToString() overload won't be available. If that's the case, do this instead:
txtOrderDate.Text = DirectCast(dt.Rows(0).Item("OrderDate"), DateTime).ToString("MM/dd/yyyy")

Related

Is conversion from string to decimal needed and if so how should it be done?

I am trying to write a code for correction of entries to my SQL Server database. I am a mechanical engineering student who has a programming class and I have never programmed before so I am not sure should I convert string to decimal and how. Last 2 rows contain 2 options I came up with. Second one is what I use for pure string, first one is a modification of formatting datetime.
This is my stored procedure:
ALTER PROCEDURE [dbo].[SP_RN_O_Ispravak]
#Br_RN_O bigint,
#Datum_O DateTime OUTPUT,
#Sifra_p int OUTPUT,
#Ime_P nvarchar (30) output,
#Prezime_P NVarChar(30) OUTPUT,
#Naziv_P nvarchar (50) output,
#Adresa_P nvarchar (50) OUTPUT,
#Telefon_P NVarChar(15) OUTPUT,
#Sifra_z int OUTPUT,
#Ime_Z nvarchar (30) output,
#Prezime_Z nvarchar (30) output,
#Sifra_kul nvarchar (3) OUTPUT,
#Naziv_Kul NVarChar(20) OUTPUT,
#Masa_O decimal (5,0) OUTPUT,
#Vlaga_O decimal (4,1) OUTPUT,
#Hek_Masa_O decimal (3,1) OUTPUT,
#Protein_O decimal (3,1) output,
#Cijena_O decimal (3,2) output
AS
SELECT #Br_RN_O=T_Otkup.Br_RN_O,
#Datum_O=T_Otkup.Datum_O,
#Sifra_p=T_Otkup.Sifra_p,
#Sifra_z=T_Otkup.Sifra_z,
#Sifra_kul=T_Otkup.Sifra_kul,
#Masa_O=T_Otkup.Masa_O,
#Vlaga_O=T_Otkup.Vlaga_O,
#Hek_Masa_O=T_Otkup.Hek_Masa_O,
#Protein_O=T_Otkup.Protein_O
FROM T_Otkup
WHERE (T_Otkup.Br_RN_O = #Br_RN_O)
SELECT #Prezime_P=Prezime_P
FROM T_Poljoprivrednik
WHERE Sifra_P=#Sifra_p
SELECT #Prezime_z=Prezime_Z
FROM T_Zaposlenik
WHERE Sifra_Z=#Sifra_z
SELECT #Naziv_kul=Naziv_Kul
FROM T_Kultura
WHERE Sifra_Kul=#Sifra_kul
RETURN
This procedure is supposed to pull the data from the database and place it in textboxes shown in the image.visual of whati'm trying to make
I managed to use the following code to convert decimal to string:
Dim cijenao As SqlParameter = New SqlParameter("#Cijena_O", Data.SqlDbType.Decimal, 3, 2)
cijenao.Direction = Data.ParameterDirection.Output
cijenao.Value = Cijena_O.Text
cmd.Parameters.Add(cijenao)
Masa_O.Text = Format(masao.Value, "#####").ToString
Vlaga_O.Text = Format(vlagao.Value, "###.#").ToString
Hek_Masa_O.Text = Format(hmasao.Value, "##.#").ToString
Protein_O.Text = Format(proto.Value, "##.#").ToString
However, it doesn't work for 2 decimal places like this:
Cijena_O.Text = Format(cijenao.Value, "#.##").ToString
I tried using the code posted by Mary, but it get the following message:
System.Data.SqlClient.SqlException: 'Procedure or function SP_RN_O_Ispravak has too many arguments specified.'
I've cleaned up this Sub, to properly scope the connection, and make sure the Connection and Command objects get disposed (via Using). It is always best to explicitly handle the data type conversions, such as using .ToString() on the .Value property of the parameters. Note I also parse the Long before assigning it to the input parameter (although you should Google the .TryParse() method and use that).
Protected Sub ISPRAVAK_NALOGA()
Using conn As New SqlConnection(<your connection string here>)
Using cmd As New SqlCommand("SP_RN_O_Ispravak", conn) With {.CommandType = CommandType.StoredProcedure}
With cmd
.Parameters.Add("#Br_RN_O", SqlDbType.BigInt).Value = Long.Parse(Br_RN_O.Text)
.Parameters.Add("#Masa_O", Data.SqlDbType.Decimal, 5, 0)
.Parameters("#Masa_O").Direction = ParameterDirection.Output
.Parameters.Add("#Vlaga_O", Data.SqlDbType.Decimal, 4, 1)
.Parameters("#Vlaga_O").Direction = ParameterDirection.Output
conn.Open()
.ExecuteNonQuery()
Masa_O.Text = .Parameters("#Masa_O").Value.ToString
Vlaga_O.Text = .Parameters("#Vlaga_O").Value.ToString
End With
End Using
End Using
End Sub
As to your code...
Check the available overloads for the Constructors for the Parameter class. https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlparameter?view=netframework-4.8#constructors There are none that match your code. Dim masao As SqlParameter = New SqlParameter("#Masa_O", Data.SqlDbType.Decimal, 5, 0) The final parameter of the constructor with 4 parameters is a string holding the name of the source column.
A Bigint in Sql Server maps to and Int64 in .net. (A Long in vb.net) This is a good reference for mapping datatypes from Sql Server to .net. https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-data-type-mappings.
Now my code...
Declare the variable outside the using blocks.
The TryParse is a very clever method that not only test a string but fills the variable with the converted string when it succeeds. Return is functionly equivalent, in this case, to the vb.net specific Exit Sub . Return is often used in other languages (think C#).
Keep your databse objects local so you can control their closing and disposing. A Using block will do this for you even if there is an error. You don't need to create new variable for the parameters. They can be referred to by name in the Parameters collection. Set the values of maso an vlaga inside the Using block before the command is disposed.
After the database objects are duly discharges, we can set the values in the User Interface. Reguarding the .ToString method; N0 (the 0 is a zero) will give you a string containing the number with no decimal protion. The N stands for Number and the 0 is the number of decimal places. It adds commas to make the number easier to read and it will round as appropriate. See https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings for more details.
Ideally the database code and the UI code would be separated but that is for another day.
Protected Sub ISPRAVAK_NALOGA()
Dim maso As Decimal
Dim vlaga As Decimal
Dim InputNumber As Long
If Not Long.TryParse(Br_RN_O.Text, InputNumber) Then
MessageBox.Show("Please enter a valid number.")
Return
End If
Using conn As New SqlConnection("Your connection string")
Using cmd As New SqlCommand("SP_RN_O_Ispravak", conn)
cmd.CommandType = CommandType.StoredProcedure
With cmd.Parameters
.Add("#Br_RN_O", SqlDbType.BigInt).Value = InputNumber
.Add("#Masa_O", Data.SqlDbType.Decimal)
.Add("#Vlaga_O", Data.SqlDbType.Decimal)
End With
cmd.Parameters("#Vlaga_O").Direction = ParameterDirection.Output
cmd.Parameters("#Masa_O").Direction = Data.ParameterDirection.Output
conn.Open()
cmd.ExecuteNonQuery()
maso = CDec(cmd.Parameters("#Masa_O").Value)
vlaga = CDec(cmd.Parameters("#Vlaga_O").Value)
End Using
End Using
Masa_O.Text = maso.ToString("N0")
Vlaga_O.Text = vlaga.ToString
End Sub
I am a bit unsure of what you intent.
But if you want to know if you need to convert a number into a string before assigning the value to a textbox, then the answer is yes. You do need to convert it.
But there are a few things that you can do to display decimal values in a more readable way. For example, you can set the textbox customFormat to #########0.00 or ######,##0.00

Why doesn't my datatable.compute sum code work. How do I add the filter code to the Sum function

Here's my visual basic code. I have an Access database. Income table with Income Amount, MonthYr, etc columns. I have verified data is in the table and is being loaded into the dataset. There is definitely a "January 2018" value in the MonthYr column. And I also have decimal numbers in the Income amount column.
Dim sum = IncomeTable.Compute("SUM(Income Amount)", "MonthYr = January 2018")
'code above causes this error: Missing operand after '2018' operator.
Dim sum = IncomeTable.Compute("SUM(Income Amount)", "MonthYr = 'January 2018'")
'code above causes this error: Syntax error in aggregate argument: Expecting a single column argument with possible 'Child' qualifier.
Dim sum = IncomeTable.Compute("SUM(Income Amount)", "MonthYr = [January 2018]")
' code above causes this error: Cannot find column [January 2018].
-In Access, The Income Amount column is currency datatype, and MonthYr column is short text datatype
-I have tried various other things like using an _underscore to replace the spaces in column name and in "January 2018"
-I have been looking all over msdn and google and tried every variation of the code I could come up with.
Your syntax is totally off - wonder where you got that from.
It could be:
Dim SumAmount As Currency
SumAmount = DSum("[Income Amount]", "IncomeTable", "MonthYr = 'January 2018'")
In VB:
Open a recordset:
"Select Sum([Income Amount]) From IncomeTable Where MonthYr = 'January 2018'"

data type - date, int and $ in excel as blank, however load into ms SQL server as 0 (ZEROs)

In ms SQL server I created a table; date, number and money field. They are created as exA(date, null), exB(int, null), exC(money, null) respectively.
I tried to load the excel values into a table of the respective fields. However in excel when there are no date (blanks) it loaded as 0 (1900-01-01). I can't load blanks into the table because of the field as date, int, money. In the money column in excel it can be either blank or 0. But when I load it the blanks and 0 are the same, 0.00.
if I changed all the fields into varchar a blank is a blank and a 0 will be a 0. However it will be all text. But this is deceiving as it's not correct since number should really be integer, and date should be date. Keeping the format as it is, I would like blanks in excel as nothing /empty and 0 amount as 0.00. Please advise.
Below are some programming ways I tried to change it, but without success. I use vb.net to load the data from excel file into sql server.
If exA = "" Then
exA = vbEmpty
End If
mycommand.Parameters.Add(New SqlParameter("#exA", exA))
my program always end up stopping here at this bottom code. Can't execute it because in sql server is as int, date or money and vbEmpty is not the same data type. I tried nothing, it doesn't work either.
mycommand.ExecuteNonQuery()
Error message: Conversion failed when converting date and/ or time from character string. exA is from the excel date column. Thanks !
This is what I have as an answer to my own question after doing some investigation and research. However this may not be the best answer. For example, if we have more fields (for example 200) and some can be blank and others are not. In this case there needs to be a lot of if clause. It's a work around. If there are better solutions, please share.
Solution: for the one's that are blank, I don't add them to the database.
If exA <> "" Then
str = "INSERT INTO bank_CK (exA, exB, exC) VALUES(#A, #B, #C)"
cmd.Parameters.Add(New SqlParameter("#A", exA))
cmd.Parameters.Add(New SqlParameter("#B", exB))
cmd.Parameters.Add(New SqlParameter("#C", exC))
Else
str = "INSERT INTO bank_CK (exB, exC) VALUES(#B, #C)"
cmd.Parameters.Add(New SqlParameter("#B", exB))
cmd.Parameters.Add(New SqlParameter("#C", exC))
End If
Or I could import the data as varchar(50) or the right data type and when requested; the data is then convert from blanks to NULL or data type varchar(50) for date, integer, and money to numbers or date as I have below with an SQL statement:
SELECT COALESCE(CAST(NULLIF(ISNUMERIC(moneyFIELDasTEXT), 1) AS MONEY), moneyFIELDasTEXT) as moneyFIELDasTEXT,
anotherFIELD,
CASE
WHEN
ddate <> ''
THEN
ddate
END as ddate,
CASE
WHEN
twage <> ''
THEN
COALESCE(CAST(NULLIF(ISNUMERIC(twage), 1) AS MONEY), twage)
END as twage,
CASE
WHEN
wdate <> ''
THEN
cast(wdate as date)
END as wdate,
CASE
WHEN
ddate <> ''
THEN
convert(varchar(50),ddate, 102)
END as ddate,
CASE
WHEN
tamt<> ''
THEN
COALESCE(CAST(NULLIF(ISNUMERIC(tamt), 1) AS MONEY), tamt)
END as tamt
FROM table
WHERE rdate = ''

convert string date to date type in sql server 2012

In a school website, I want to enable the admin to filter students based on date range when they were born. Dates in my tblStudent are stored as strings, so I cannot use:
SELECT ts.Name from tblStudent ts WHERE ts.BirthDay>'1367/01/31' AND ts.BirthDay<'1377/01/31'
I have saved dates (Jalali Format) in database table tblStudent. I need to do comparison based on dates. So I need to convert date strings to date type in sql server. To this purpose I used:
SELECT convert(date,tblStudent.BirthDay) from tblStudent
However,It stops after 27 results with the following error
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
I have the following date strings in my tblStudent table.
1379/09/01
1375/04/20
1378/03/02
1378/03/21
1378/04/18
1378/04/18
1378/05/05
1375/04/20
1379/01/03
1378/03/01
1370/09/09
1378/03/22
1375/09/15
1379/09/01
1379/09/10
1375/04/08
1375/05/06
1370/09/09
1379/10/10
1375/04/10
1375/11/01
1375/04/04
1375/08/11
1375/05/05
1376/09/19
1375/12/12
1376/01/13
1375/15/10
1375/04/14
1375/04/04
1375/05/14
1374/11/11
1375/05/30
1375/05/14
1377/12/13
1377/02/31
1377/12/14
1377/01/13
1375/05/31
1377/11/05
1377/07/05
1375/05/31
1377/03/01
1377/04/01
1377/05/02
1377/05/04
1377/03/03
1377/01/14
1377/05/30
1377/04/31
1375/05/30
1376/06/12
1375/12/10
1377/08/14
1377/03/04
1375/04/08
1375/07/18
1375/08/09
1375/09/12
1375/11/12
1376/12/12
1375/01/02
1375/05/09
1375/04/09
1376/01/01
1375/01/30
1377/04/04
1375/05/23
1375/05/01
1377/02/01
1367/12/05
1375/05/31
1373/03/29
1373/03/03
1375/05/05
Is there a way to convert these string dates to date type and then compare them with some query? For example, such a query can be:
SELECT ts.Name from tblStudent ts where ts.BirthDay>'1375/05/31'
I think you can make them ints and compare them:
SELECT ts.Name
FROM tblStudent ts
WHERE CONVERT(INT,REPLACE(ts.BirthDay,'/','') > 13670131
AND CONVERT(INT,REPLACE(ts.BirthDay,'/','') < 13770131
Or for your second example:
SELECT ts.Name
FROM tblStudent ts
WHERE CONVERT(INT,REPLACE(ts.BirthDay,'/','') > 13750531
This would work because having the order Year-Month-Day will ensure that the int representation of a later time will be greater than the int representation of an earlier time.
I really do not know if this is the best idea, but it is an idea of how to do it. After all you would be using a conversion.
From C# you have a few options:
If your input is string:
var dateInt = Int32.Parse(dateString.Replace("/",""));
If your input is Date then:
var dateInt = Int32.Parse(dateValue.ToString("yyyyMMdd"));
You could also pass the string itself in the db and let the db do the work for you :
DECLARE #Date AS VARCHAR(10)
SET #Date = ...--This will be filled with the inputed string
DECLARE #DateINT AS INT
SET #DateINT = CONVERT(INT,REPLACE(#Date,"/",""))

sql server date in the format yyyy-MM-ddThh:mm:ssZ

I need to format a set of dates in SQL server to the following format..
yyyy-MM-ddThh:mm:ssZ
I cant seem to find how to format the date with the T and Z parts included in the string
Any ideas how to achieve this format in a SQL query?
According to the SQL Server 2005 books online page on Cast and Convert you use date format 127 - as per the example below
CONVERT(varchar(50), DateValueField, 127)
SQL Server 2000 documentation makes no reference to this format - perhaps it is only available from versions 2005 and up.
Note on the time zone added to the end (from note 7 in the docs): The optional time zone indicator, Z, is used to make it easier to map XML datetime values that have time zone information to SQL Server datetime values that have no time zone. Z is the indicator for time zone UTC-0. Other time zones are indicated with HH:MM offset in the + or - direction. For example: 2006-12-12T23:45:12-08:00.
Thanks to Martin for this note: You should be able to use STUFF to remove the miliseconds as these will be in a fixed position from the left of the string. i.e.
SELECT STUFF(CONVERT(VARCHAR(50),GETDATE(), 127) ,20,4,'')
DECLARE #SampleDate DATETIME2(3) = '2020-07-05 23:59:59';
SELECT CONVERT(VARCHAR(20), CONVERT(DATETIMEOFFSET, #SampleDate), 127);
--results: 2020-07-05T23:59:59Z
You can parse C# output in SQL using below:
SELECT CONVERT(DATETIME, CONVERT(DATETIMEOFFSET,'2017-10-27T10:44:46Z'))
Use C# to generate this using the following:
string ConnectionString = "Data Source=SERVERNAME; Initial Catalog=DATABASENAME; Persist Security Info=True; User ID=USERNAME; Password=PASSWORD";
using(SqlConnection conn = new SqlConnection(ConnectionString))
{
DateTime d = DateTime.Now;
string Query = "SELECT CONVERT(DATETIME, CONVERT(DATETIMEOFFSET,'" + d.ToString("yyyy-MM-dd") + "T" + d.ToString("HH:mm:ss") + "Z'))"
conn.Open();
using(SqlCommand cmd = new SqlCommand(Query, conn))
{
using(SqlDataReader rdr = cmd.ExecuteReader())
{
if(rdr.HasRows)
{
while(rdr.Read())
{
for(int i; i < rdr.length; i++)
{
Console.WriteLine(rdr[0].ToString());
}
}
//DataTable dt = new DataTable(); dt.Load(rdr); //Alternative method if DataTable preferred
}
}
}
}
select left(convert(varchar(30),getdate(),126)+ '.000',23)
Try this
SELECT STUFF(
CONVERT(datetime2(0), GETDATE(), 126)
AT TIME ZONE 'US Eastern Standard Time'
,11,1,'T')
on MSSQL
SELECT FORMAT( GETDATE(),'yyyy-MM-ddTHH:mm:ss.ms zzzz')

Resources