使用T-SQL生成随机字符串

时间:2017-08-22 07:16:14

标签: sql-server tsql random casting

DECLARE @tmp char(1) = '';
SET @tmp = CAST(RAND()*26 AS int)+97;

此代码不起作用。 select的相同表达式效果很好:

SELECT CAST(RAND()*26 AS int)+97;

可能是我的@tmp声明了错误的数据类型?

4 个答案:

答案 0 :(得分:1)

尝试将@tmp声明为int而不是char(1)

DECLARE @tmp int = '';
SET @tmp = CAST(RAND()*26 AS int)+97;
SELECT @tmp

答案 1 :(得分:0)

我认为您需要CHAR功能:

  

CHAR(integer_expression)

     

将int ASCII代码转换为字符。

private void setAnswers( double total1, double total2 ){
    setAnswer(answer, "Total Area Allocation = " + total1 + " ha");
    setAnswer(answer2, "Set break " + total2 + " m");
}

private void setAnswer( TextView view, String text  ) {
    view.setBackgroundColor(Color.parseColor("#d6ffffff"));
    view.setText(text);
}

<强> Rextester Demo

答案 2 :(得分:0)

这可能会帮助你:

DECLARE @tmp nvarchar(38) = '';
SET @tmp = newid()
select @tmp

答案 3 :(得分:0)

试试这个:

DECLARE @tmp varchar(3)= CAST(RAND()*26 AS int)+97;
select @tmp;

或者您也可以尝试将数据类型更改为int

DECLARE @tmp int= CAST(RAND()*26 AS int)+97;
select @tmp;