How to Concatenate Numbers and Strings to Format Numbers in T-SQL?

后端 未结 10 2009
借酒劲吻你
借酒劲吻你 2020-11-30 03:45

I have the following function

ALTER FUNCTION [dbo].[ActualWeightDIMS]
(
    -- Add the parameters for the function here
    @ActualWeight int,
    @Actual_D         


        
相关标签:
10条回答
  • 2020-11-30 03:57

    Change this:

    SET @ActualWeightDIMS= @Actual_Dims_Lenght + 'x' + 
        @Actual_Dims_Width + 'x' + @Actual_Dims_Height;
    

    To this:

    SET @ActualWeightDIMS= CAST(@Actual_Dims_Lenght as varchar(3)) + 'x' + 
        CAST(@Actual_Dims_Width as varchar(3)) + 'x' + 
        CAST(@Actual_Dims_Height as varchar(3));
    

    Change this:

    SET @ActualWeightDIMS = @ActualWeight;
    

    To this:

    SET @ActualWeightDIMS = CAST(@ActualWeight as varchar(50));
    

    You need to use CAST. Learn all about CAST and CONVERT here, because data types are important!

    0 讨论(0)
  • 2020-11-30 04:01

    A couple of quick notes:

    • It's "length" not "lenght"
    • Table aliases in your query would probably make it a lot more readable

    Now onto the problem...

    You need to explicitly convert your parameters to VARCHAR before trying to concatenate them. When SQL Server sees @my_int + 'X' it thinks you're trying to add the number "X" to @my_int and it can't do that. Instead try:

    SET @ActualWeightDIMS =
         CAST(@Actual_Dims_Lenght AS VARCHAR(16)) + 'x' +
         CAST(@Actual_Dims_Width  AS VARCHAR(16)) + 'x' +
         CAST(@Actual_Dims_Height  AS VARCHAR(16))
    
    0 讨论(0)
  • 2020-11-30 04:01

    You must cast your integers as string when trying to concatenate them into a varchar.

    i.e.

     SELECT  @ActualWeightDIMS = CAST(@Actual_Dims_Lenght AS varchar(10)) 
                                  + 'x' + 
                                 CAST(@Actual_Dims_Width as varchar(10)) 
                                 + 'x' + CAST(@Actual_Dims_Height as varchar(10));
    

    In SQL Server 2008, you can use the STR function:

       SELECT  @ActualWeightDIMS = STR(@Actual_Dims_Lenght) 
                                  + 'x' + STR(@Actual_Dims_Width) 
                                  + 'x' + STR(@Actual_Dims_Height);
    
    0 讨论(0)
  • 2020-11-30 04:09

    If you are using SQL Server 2012+ you can use CONCAT function in which we don't have to do any explicit conversion

    SET @ActualWeightDIMS = Concat(@Actual_Dims_Lenght, 'x', @Actual_Dims_Width, 'x' 
                            , @Actual_Dims_Height) 
    
    0 讨论(0)
  • 2020-11-30 04:09
    select 'abcd' + ltrim(str(1)) + ltrim(str(2))
    
    0 讨论(0)
  • 2020-11-30 04:10

    You need to CAST your numeric data to strings before you do string concatenation, so for example use CAST(@Actual_Dims_Lenght AS VARCHAR) instead of just @Actual_Dims_Lenght, &c.

    0 讨论(0)
提交回复
热议问题