Convert DateTime to a different format in sql - asp.net

How can I convert/cast this datetime format: 06/17/2012 12:00:00 AM
To this date format : 2012/06/17
in a SQL Update Statement?
I need to change to fields. BeginDate, and EndDate. Both DateTime Types.
This is my Update statement so far:
Update discount set DiscountPromotionalID = #DiscountPromotionalID,
isActive =#isActive, Title = #Title, BeginDate = #BeginDate, EndDate = #EndDate,
DiscountPercentage = #DiscountPercentage
where DiscountPromotionalID = #DiscountPromotionalID;"

If you're storing it as NVARCHAR (which you shouldn't be) you can use the following to convert it when your doing your insert/update statement. I would recommend converting this column to a proper DateTime field then you can format as you wish within the presentation layer as commentors have suggested.
Checkout this resource for all your SQL Data Formatting needs (with example sql!)
http://www.sql-server-helper.com/tips/date-formats.aspx
I believe you're looking for something like this (from the resource above):
CONVERT(VARCHAR(10), GETDATE(), 111) AS [YYYY/MM/DD]

Like a C# DateTime value, a SQL Server DateTime value has no format: it's just a 64-bit field consisting of two 32-bit integers. The first counts days since the epoch (1 January 1900 00:00:00.000); the second counts time since start of day in 1/300ths of a second.
You apply formatting when you display it or convert it to char/varchar, either in SQL using CONVERT(), or in the client code.
Your update statement doesn't care about format: it cares about value. If you pass a C# DateTime value as a SqlParameter to your stored procedure or parameterized query, the Right Thing will happen: the CLR will magically translate the one into the other for you.
If, you pass a string as the DateTime parameter from C#, it needs to be in a format that SQL Server will recognize as a DateTime string. Assuming that's the case, the conversion from C# string to SQL Server DateTime value will likewise happen magically.
Given your update statement, code something like the following ought to do you:
public int UpdateDiscount( int discountPromotionalID , bool isActive , string title , DateTime beginDate , DateTime endDate , int discountPercentage )
{
const string updateQuery = #"
Update discount
set DiscountPromotionalID = #DiscountPromotionalID ,
isActive = #isActive ,
Title = #Title ,
BeginDate = #BeginDate ,
EndDate = #EndDate ,
DiscountPercentage = #DiscountPercentage
where DiscountPromotionalID = #DiscountPromotionalID
" ;
int rowsAffected ;
using ( SqlConnection connection = new SqlConnection( SomeConnectString ) )
using ( SqlCommand cmd = connection.CreateCommand() )
{
cmd.CommandText = updateQuery ;
cmd.CommandType = CommandType.Text ;
cmd.Parameters.AddWithValue( "#DiscountPromotionalID" , discountPromotionalID ) ;
cmd.Parameters.AddWithValue( "#isActive" , isActive ? 1 : 0 ) ; // C# bools are true/false; SQL bools are 1/0
cmd.Parameters.AddWithValue( "#Title" , title ) ;
cmd.Parameters.AddWithValue( "#BeginDate" , beginDate ) ;
cmd.Parameters.AddWithValue( "#EndDate" , endDate ) ;
cmd.Parameters.AddWithValue( "#DiscountPercentage" , discountPercentage ) ;
connection.Open() ;
rowsAffected = cmd.ExecuteNonQuery() ;
connection.Close() ;
}
return rowsAffected ;
}

Related

While loop in stored procedure in sql returns only one row to grid view in asp.net

Using while loop in stored procedure works correctly in SQL server but returns only first row to asp.net grid view.
My stored procedure
create procedure [dbo].[DoorDetails]
#emp varchar(16),
#fromdate datetime,
#todate datetime,
#cdate datetime =#fromdate
as
while #cdate<= #todate
Begin
select convert(varchar,(CONVERT(date,#cdate,103)),103) as Date, Empname, min(TransactionDateTime) as EntryTime ,max(TransactionDateTime) as ExitTime,
(DateDIFF (MINUTE,min(TransactionDateTime), max(TransactionDateTime)))/60 as Hours,
(DateDIFF (MINUTE,min(TransactionDateTime), max(TransactionDateTime)))%60 as minutes from
ceptEmpTxn where EmpName = #emp and cast(TransactionDateTime as Date)=cast(#cdate as date) group by empname
SET #cdate = DATEADD(dd,1,#cdate)
end
GO
Result in SQL
-------------------------------------------------------------------------------------------------------------
|Date| |Empname| |EntryTime| |ExitTime| |Hours| minutes|
|14/09/2016| |PRAVEEN KUMAR| |2016-09-14 09:28:13.000||2016-09-14 18:42:14.000 9 14
------------------------------------------------------------------------------------------------------------
|Date| |Empname| |EntryTime| |ExitTime| |Hours| minutes|
|15/09/2016| |PRAVEEN KUMAR| |2016-09-15 09:27:13.000||2016-09-15 17:16:46.000 7 49
-------------------------------------------------------------------------------------------------------------
|Date| |Empname| |EntryTime| |ExitTime| |Hours| minutes|
|16/09/2016| |PRAVEEN KUMAR| |2016-09-16 09:30:33.000||2016-09-16 19:03:14.000 9 33
Headers are repeating each time in sql
Result in Webpage (using Grid view)
------------------------------------------------------------------------
Date| Empname| EntryTime| ExitTime| Hours| minutes|
15/09/2016| PRAVEEN KUMAR| 15-09-2016 09:27:07| 15-09-2016 17:16:46| 7| 49|
My function in asp.net
public DataTable tottime(string empname, DateTime fromdate, DateTime todate)
{
System.Data.SqlClient.SqlConnection myConn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["ceptConnectionString"].ConnectionString.ToString());
DataTable myDt = new DataTable();
System.Data.SqlClient.SqlCommand myCmd = new System.Data.SqlClient.SqlCommand();
myCmd.CommandType = System.Data.CommandType.StoredProcedure;
System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter();
myCmd.CommandText = "DoorDetails";
myCmd.Parameters.AddWithValue("#emp", empname);
myCmd.Parameters.AddWithValue("#fromdate", fromdate);
myCmd.Parameters.AddWithValue("#todate", todate);
da.SelectCommand = myCmd;
try
{
myCmd.Connection = myConn;
da.Fill(myDt);
return myDt;
}
catch (Exception ex)
{
throw;
}
finally
{
myDt = null;
da.Dispose();
myCmd.Dispose();
myConn.Close();
myConn.Dispose();
}
}
How to return all the values from stored procedure also how to have table header only once followed by all the rows.
Possibly you may have to create a table variable and store the result set there and again fetch that result set at the end. Try this.
P.S Please change the data types of table variable (#t) columns accordingly. So that there will not be any troubles.
create procedure [dbo].[DoorDetails]
#emp varchar(16),
#fromdate datetime,
#todate datetime,
#cdate datetime =#fromdate
as
while #cdate<= #todate
Begin
DECLARE #T TABLE
(
[Date] Date
,Empname VARCHAR(200)
,EntryTime DATETIME
,ExitTime DATETIME
,[Hours] INT
,[minutes] INT
)
INSERT INTO #T
select convert(varchar,(CONVERT(date,#cdate,103)),103) as Date
, Empname, min(TransactionDateTime) as EntryTime
,max(TransactionDateTime) as ExitTime
,(DateDIFF (MINUTE,min(TransactionDateTime), max(TransactionDateTime)))/60 as Hours
,(DateDIFF (MINUTE,min(TransactionDateTime), max(TransactionDateTime)))%60 as minutes
from
ceptEmpTxn where EmpName = #emp and cast(TransactionDateTime as Date)=cast(#cdate as date) group by empname
SET #cdate = DATEADD(dd,1,#cdate)
end
SELECT * FROM #T
GO

How to separate (split) string with comma in SQL Server stored procedure

I have a checkboxlist. The selected (checked) items are stored in List<string> selected.
For example, value selected is monday,tuesday,thursday out of 7 days
I am converting List<> to a comma-separated string, i.e.
string a= "monday,tuesday,thursday"
Now, I am passing this value to a stored procedure as a string. I want to fire query like:
Select *
from tblx
where days = 'Monday' or days = 'Tuesday' or days = 'Thursday'`
My question is: how to separate string in the stored procedure?
If you pass the comma separated (any separator) string to store procedure and use in query so must need to spit that string and then you will use it.
Below have example:
DECLARE #str VARCHAR(500) = 'monday,tuesday,thursday'
CREATE TABLE #Temp (tDay VARCHAR(100))
WHILE LEN(#str) > 0
BEGIN
DECLARE #TDay VARCHAR(100)
IF CHARINDEX(',',#str) > 0
SET #TDay = SUBSTRING(#str,0,CHARINDEX(',',#str))
ELSE
BEGIN
SET #TDay = #str
SET #str = ''
END
INSERT INTO #Temp VALUES (#TDay)
SET #str = REPLACE(#str,#TDay + ',' , '')
END
SELECT *
FROM tblx
WHERE days IN (SELECT tDay FROM #Temp)
Try this:
CREATE FUNCTION [dbo].[ufnSplit] (#string NVARCHAR(MAX))
RETURNS #parsedString TABLE (id NVARCHAR(MAX))
AS
BEGIN
DECLARE #separator NCHAR(1)
SET #separator=','
DECLARE #position int
SET #position = 1
SET #string = #string + #separator
WHILE charindex(#separator,#string,#position) <> 0
BEGIN
INSERT into #parsedString
SELECT substring(#string, #position, charindex(#separator,#string,#position) - #position)
SET #position = charindex(#separator,#string,#position) + 1
END
RETURN
END
Then use this function,
Select *
from tblx
where days IN (SELECT id FROM [dbo].[ufnSplit]('monday,tuesday,thursday'))
try this
CREATE FUNCTION Split
(
#delimited nvarchar(max),
#delimiter nvarchar(100)
) RETURNS #t TABLE
(
-- Id column can be commented out, not required for sql splitting string
id int identity(1,1), -- I use this column for numbering splitted parts
val nvarchar(max)
)
AS
BEGIN
declare #xml xml
set #xml = N'<root><r>' + replace(#delimited,#delimiter,'</r><r>') + '</r></root>'
insert into #t(val)
select
r.value('.','varchar(max)') as item
from #xml.nodes('//root/r') as records(r)
RETURN
END
GO
usage:
select * from tblx where days in (select val from dbo.split('monday,tuesday,thursday',','))
I think you want this
SELECT * FROM tblx where days in ('Monday','Tuesday','Thursday')
you can get it like this:
var a = "monday,tuesday,thursday";
var sql = string.Format("Select * from tblx where days IN ('{0}')", string.Join("','",a.Split(new[] {','})));
I face the same problem, and i try all the way but not get expected solution. Finally i did like follow. Try it hope it will work...
create Function [dbo].[Split]
(
#RowData NVARCHAR(MAX),
#SplitOn NVARCHAR(5)
)
RETURNS #RtnValue TABLE
(
Id INT IDENTITY(1,1),
Data NVARCHAR(100)
)
AS
BEGIN
DECLARE #Cnt INT
SET #Cnt = 1
WHILE (Charindex(#SplitOn,#RowData)>0)
BEGIN
INSERT INTO #RtnValue (data)
SELECT Data = ltrim(rtrim(Substring(#RowData,1,Charindex(#SplitOn,#RowData)-1)))
SET #RowData = Substring(#RowData,Charindex(#SplitOn,#RowData)+1,len(#RowData))
SET #Cnt = #Cnt + 1
END
INSERT INTO #RtnValue (data)
SELECT Data = ltrim(rtrim(#RowData))
RETURN
END
And in the store procedure put the code like that.
select #ActualTarget= count(*) from UpdateVisitDetails where CreatedBy IN (SELECT [DATA] FROM [dbo].[Split](#AllDATS,',' ))
I have same problem. I tried this.. and this was properly run
ALTER FUNCTION [dbo].[Split]
(
#List varchar(max),
#SplitOn nvarchar(5)
)
RETURNS #RtnValue table
(
Id int identity(1,1),
Value nvarchar(max)
)
AS
BEGIN
IF (len(#List) <=0)
Begin
Return
End
While (Charindex(#SplitOn,#List)>0)
Begin
Insert Into #RtnValue (value)
Select
Value = ltrim(rtrim(Substring(#List,1,Charindex(#SplitOn,#List)-1)))
Set #List = Substring(#List,Charindex(#SplitOn,#List)+len(#SplitOn),len(#List))
End
Insert Into #RtnValue (Value)
Select Value = ltrim(rtrim(#List))
Return
END
Run :
SELECT * FROM dbo.Split('Apple,Banana,Mango',',')
Output:

Getting error while inserting table in database?

i am inserting table in database using table datatype with the following code:
CREATE TYPE BackUpDoctorLocationAreaRoom AS TABLE (
[RoomId] bigint,
[AreaId] bigint,
[LocationId] bigint
);
Alter proc proc_tblBackUpDoctorInsert
(
#Id uniqueidentifier='',
#BackUpDoctorId uniqueidentifier='1323e1f4-7a93-4b45-9a9b-3840c32fd6d8',
#StartDate datetime='11/08/2012',
#EndDate datetime='11/09/2012',
#StartTime datetime='22:22:22',
#EndTime datetime='01:11:11',
#CreatedBy uniqueidentifier='acf7961c-4111-49ad-a66a-ce7f9ce131bd',
#ModifiedBy uniqueidentifier='acf7961c-4111-49ad-a66a-ce7f9ce131bd',
#createdDate datetime='11/6/12 3:09:58 AM',
#ModifiedDate datetime='11/6/12 3:09:58 AM',
#tblBackUpDoctorsForRooms BackUpDoctorLocationAreaRoom READONLY
)
as
set xact_abort on
declare #newId uniqueidentifier;
set #newId = newid();
insert into tblBackUpDoctor (Id,BackUpDoctorId,StartDate,EndDate,StartTime,EndTime,CreatedBy,ModifiedBy,
createdDate,ModifiedDate,IsActive,isdeleted) values
(#newId,
#BackUpDoctorId,
#StartDate,
#EndDate,
#StartTime,
#EndTime,
#CreatedBy,
#ModifiedBy,
#createdDate,
#ModifiedDate,
1,0)
declare #IdFortblBackUpDoctorsForRooms uniqueidentifier;
set #IdFortblBackUpDoctorsForRooms = newid();
delete from tblBackUpDoctorsForRooms where BackUpRecordId=#id and Roomid in (Select roomid from #tblBackUpDoctorsForRooms)
delete from tblbackupdoctor where id=#id
insert into tblBackUpDoctorsForRooms (BackUpRecordId,Roomid,Araeid,locationid)
Select #newId,roomid,areaid,locationid from #tblBackUpDoctorsForRooms
select #newId
This is the sp in which i am using that table.
My class file's code is :
public string InsertBackUpDoctor(ClsBackUpDoctorProp objProp, DataTable dtLocAreaRoom)
{
String ConnectionString = CCMMUtility.GetCacheForWholeApplication();
String backUpRecordId = "";
SqlParameter[] param = new SqlParameter[12];
param[0] = new SqlParameter("#Id", objProp.Id);
param[1] = new SqlParameter("#BackUpDoctorId", objProp.BackUpDoctorId);
param[2] = new SqlParameter("#StartDate", objProp.StartDate);
param[3] = new SqlParameter("#EndDate", objProp.EndDate);
param[4] = new SqlParameter("#StartTime", objProp.StartTime);
param[5] = new SqlParameter("#EndTime", objProp.EndTime);
param[6] = new SqlParameter("#CreatedBy", objProp.CreatedBy);
param[7] = new SqlParameter("#ModifiedBy", objProp.ModifiedBy);
param[8] = new SqlParameter("#createdDate", CCMMUtility.GetCurrentDateTimeByTimeZone("US Mountain Standard Time"));
param[9] = new SqlParameter("#ModifiedDate", CCMMUtility.GetCurrentDateTimeByTimeZone("US Mountain Standard Time"));
param[10] = new SqlParameter("#CurrentDate", objProp.CurrentDate);
param[11] = new SqlParameter("#tblBackUpDoctorsForRooms ", dtLocAreaRoom);
backUpRecordId = SqlHelper.ExecuteScalar(ConnectionString, "proc_tblbackupdoctorInsertBackUpDoctors", param).ToString();
return backUpRecordId;
}
and here is the error which is coming when i tries to insert :
The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Table-valued parameter 12 ("#tblBackUpDoctorsForRooms"), row 0, column 0: Data type 0xF3 (user-defined table type) has a non-zero length database name specified. Database name is not allowed with a table-valued parameter, only schema name and type name are valid.
I dont know why this coming please help me..
I believe you'd have to change the way you pass your custom parameter:
Not just
param[11] = new SqlParameter("#tblBackUpDoctorsForRooms ", dtLocAreaRoom);
but rather something like
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#tblBackUpDoctorsForRooms";
parameter.SqlDbType = System.Data.SqlDbType.Structured;
parameter.TypeName = "BackUpDoctorLocationAreaRoom";
parameter.Value = dtLocAreaRoom;
param[11] = parameter;
try
parameter.SqlDbType = System.Data.SqlDbType.Structured;
parameter.TypeName = "BackUpDoctorLocationAreaRoom";
and in the call add
backUpRecordId = SqlHelper.ExecuteScalar(ConnectionString,CommandType.StoredProcedure
"proc_tblbackupdoctorInsertBackUpDoctors", param).ToString();

Output parameter used to insert a row in same table

Thanks for your help Guys
I am working on a Asp.net based project and my requiremnent is to generate a PARTNO with the combination of MaterialType+ProductID and - 4digit random number
NOTE: ProductID is Primary key and also set it to output parameter
for example If material type is 500 and product ID generated 55 and random no generated 5434, then part no become 555-5434
Now my question is how could I store partno in same table, I am somewhat trying like that
Connection.Open()
Dim trn As SqlClient.SqlTransaction
trn = Connection.BeginTransaction
Using trn
Dim sqlcode As New SqlParameter("#ProductID", Products.ProductID)
sqlcode.Direction = ParameterDirection.InputOutput
Using Command As New SqlCommand("Product_Write", Connection, trn)
Command.CommandType = CommandType.StoredProcedure
Command.Parameters.Add(sqlcode) Command.Parameters.AddWithValue("#MaterialType", Materialtype.MaterialTypeCode)
Command.Parameters.AddWithValue("#CategoryID", category.CategoryId)
Command.Parameters.AddWithValue("#ProductName", Products.ProductName)
Command.Parameters.AddWithValue("#ProductDescription", Products.ProductDescription)
Command.Parameters.AddWithValue("#ProductActive", Products.ProductActive)
Command.Parameters.AddWithValue("#ProductImage", Products.ProductImage)
Command.Parameters.AddWithValue("#PartNo", 0)
Command.ExecuteNonQuery()
Products.ProductID = CInt(sqlcode.Value)
'Insert the part no
Dim random As New Random()
Dim value As Integer = random.Next(9999)
Dim PartNo As String = CType((Materialtype.MaterialTypeCode + Products.ProductID).ToString + "-" + value.ToString, String)
'Dont know what to do
trn.Commit()
Connection.Close()
End Using
End Using
End Using
Return Products
End Function
ALTER PROCEDURE [dbo].[Product_Write]
#ProductID bigint OUTPUT,
#MaterialType int,
#CategoryID bigint,
#ProductName VARCHAR(MAX),
#ProductDescription VARCHAR(MAX),
#ProductActive Bit,
#ProductImage VARCHAR(MAX),
#PartNo VARCHAR(30)
AS
IF (#ProductID=0)
BEGIN
INSERT INTO T_Product(
MaterialType,
CategoryID,
ProductName,
ProductDescription,
ProductActive,
ProductImage,
PartNo)
VALUES(
#MaterialType,
#CategoryID,
#ProductName,
#ProductDescription,
#ProductActive,
#ProductImage,
#PartNo)
SET #ProductID=SCOPE_IDENTITY()
END
ELSE
UPDATE T_Product SET
MaterialType=#MaterialType,
CategoryID=#CategoryID,
ProductName=#ProductName,
ProductDescription=#ProductDescription,
ProductActive=#ProductActive,
ProductImage=#ProductImage,
PartNo=#PartNo
WHERE ProductID=#ProductID
Please help me out
Thanks
If you can update the Stored Procedure you would need something along these lines
declare #id int
set #id = SCOPE_IDENTITY()
UPDATE <Table> Set PartNo = MaterialType + convert(varchar(max),#id) + convert(varchar(4),CEILING(9999*RAND())) Where ID = #id

ExecuteNonQuery() ERROR -> The conversion of the nvarchar value '3955811801' overflowed an int column.

My code is as shown below :
using (SqlConnection _conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DarmanConnectionString"].ToString()))
{
using (SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add(new SqlParameter("#Co_ID", int.Parse(Session["Co_ID"].ToString())));
_cmd.Parameters.Add(new SqlParameter("#RETURN_VALUE", SqlDbType.NVarChar));
_cmd.Parameters["#RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;
_conn.Open();
_cmd.ExecuteNonQuery();
Int64 result = Int64.Parse(_cmd.Parameters["#RETURN_VALUE"].Value.ToString());
lblSumTotalPayShow.Text = result.ToString();
_conn.Close();
}
}
my SP is like this :
create Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
#Co_ID int
As
-----------------
Declare #Sum nvarchar(50)
-----------------
BEGIN
Select #Sum = convert(nvarchar(50), SUM(TotalPay))
From Noskheh
Where (Co_ID = #Co_ID)
Return #Sum
END
and the error is in line (_cmd.ExecuteNonQuery();):
Error:
Sys.WebForms.PageRequestManagerServerErrorException: The conversion of
the nvarchar value '3955811801' overflowed an int column. The
'sp_Noskheh_SumOfTotalPay' procedure attempted to return a status of
NULL, which is not allowed. A status of 0 will be returned instead.
Would you please help me to figure out this problem?
Change #Co_ID to bigint. 3955811801 is higher then 2^31-1
The SUM is greater than 2^31-1. The RETURN tries to convert it to int and fails.
Use an OUTPUT parameters or just return a recordset.
Like this
create Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
#Co_ID int,
#Sum nvarchar(50) OUTPUT --or bigint?
As
BEGIN
Select
#Sum = convert(nvarchar(50), SUM(TotalPay))
From Noskheh
Where
(Co_ID = #Co_ID)
END
or
create Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
#Co_ID int
As
BEGIN
Select
SUM(TotalPay) AS SumTotalPay
From Noskheh
Where
(Co_ID = #Co_ID)
END
You are trying to convert a nvarchar value to a int
The Return statement must be an integer.
Try changing your approach and in your Stored Proc do
Select #Sum instead of return #sum
Then instead of using ExecuteNonQuery use ExecuteScalar
String result = (String)cmd.ExecuteScalar();
lblSumTotalPayShow.Text = result.ToString();
If the problem is not the #Co_ID as others indicate, then maybe the SUM(TotalPay) might be equal to your 3.9 billion value. if the TotalPay column is an integer, the SUM is integer before converting to varchar.

Resources