Monday, 6 June 2016

How to convert from decimal to binary in SQL Server? Write the Script/Query, Interview Question 2016

Write a function to convert decimal number to binary number in SQL Server? (asked during Genpact interview Jun 2016)

Ans:



CREATE FUNCTION fn_ConvertFromDecimal2Binary
( @Num int )
RETURNS VARCHAR(30)
AS
BEGIN
DECLARE @quot int
DECLARE @Rem int
DECLARE @Res varchar(30) = ''
Set @quot= @Num

While(@quot>1)
BEGIN
SET @Rem = @quot%2
SET @quot = @quot/2
SET @Res= CONVERT(varchar(30),@Rem)+ @Res
END
SET @Res = (CONVERT(varchar(30),@quot) + @Res)
RETURN @Res
END

GO
Visit Our New Site for HR Interview Questions Answers http://www.interviewboat.com/Company/GetCompany
Sponsored Ads

1 comment:

  1. CREATE FUNCTION fn_ConvertFromDecimal2Binary
    ( @Num int )
    RETURNS VARCHAR(30)
    AS
    BEGIN
    DECLARE @quot int
    DECLARE @Rem int
    DECLARE @Res varchar(30) = ''
    Set @quot= @Num

    While(@quot>1)
    BEGIN
    SET @Rem = @quot%2
    SET @quot = @quot/2
    SET @Res= CONVERT(varchar(30),@Rem)+ @Res
    END
    SET @Res = (CONVERT(varchar(30),@quot) + @Res)
    RETURN @Res
    END

    GO

    ReplyDelete