Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Converting int to varchar

I need help converting an integer to a varchar.

I'm trying to write a procedure that takes in a ProfileID and a Currenttime; using those two values it finds the start time of the profileID and subtracts currenttime from starttime and returns hours:minutes:seconds.

What am I doing wrong, is there a better way to write this?

Thanks.

CREATE PROCEDURE [dbo].[CalculateElaspedTime]
    -- Add the parameters for the stored procedure here
    @ProfileID nvarchar(10),
    @CurrentDateTime datetime = '' 
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    if @CurrentDateTime = CAST('' as datetime)
    set @CurrentDateTime = GETDATE()

    DECLARE @StartTime datetime;
    DECLARE @ElaspedTime time;
    DECLARE @hh int;
    DECLARE @mm int;
    DECLARE @ss int;
    Declare @TimeString varchar
    set @StartTime = (Select top 1 [DateTime] From Log WHERE ProfileID = @ProfileID);
    set @hh = DateDiff(hour,@StartTime,@CurrentDateTime);
    set @mm = DateDiff(minute,@StartTime,@CurrentDateTime)-60*@hh;
    set @ss = DateDiff(second,@StartTime,@CurrentDateTime)-60*@mm;

    set @TimeString = (Select CAST(@hh as varchar)); -- Fails Here 
    set @ElaspedTime = convert(datetime, cast(@hh as varchar) + ':' + cast(@mm as varchar) + ':' + cast(@ss as varchar));
    INSERT INTO Log (ElaspedTime) Values (@ElaspedTime);
END
like image 639
Pat Avatar asked Jun 21 '26 14:06

Pat


1 Answers

Try this. All of that excitement in the function may be unnecessary.

CONVERT(varchar(10),(@CurrentDateTime-@Start_Time),108)
like image 70
Eric Hauenstein Avatar answered Jun 24 '26 09:06

Eric Hauenstein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!