在T-SQL中将varchar转换为bigint

时间:2017-09-01 20:06:22

标签: sql-server type-conversion bigint

我在我的网络应用程序的SQL中做计算部分,

我有一些标量变量:

declare @calc as bigint
declare @paymentid as nvarchar(50)

我正在使用像这样的变量

set @calc =(SELECT REPLACE(CONVERT(CHAR(30), '2017-09-02', 103), '-', ''))     

此行删除'-'并将@calc中的值设置为(20170902)

set @calc = (SELECT SUBSTRING(CONVERT(char(30), '2017-09-02',112), 3, 8))    

此行提取170902并将@calc中的值设置为(170902)

set @paymentid =  CAST(@calc as nvarchar(max))+'0001'

此行将paymentid的值设置为(1709020001)

但我在这一行收到错误

set @calc = (SELECT SUBSTRING(CONVERT(char(30), '2017-09-02',112), 3, 8))    

,错误是:

  

Msg 8114,Level 16,State 5,Line 4
  将数据类型varchar转换为bigint时出错

我的整个代码看起来像这样

declare @calc as bigint
declare @paymentid as nvarchar(50)

set @calc =(SELECT REPLACE(CONVERT(CHAR(30), '2017-09-02', 103), '-', ''))     
set @calc = (SELECT SUBSTRING(CONVERT(char(30), '2017-09-02',112), 3, 8))    
set @paymentid =  CAST(@calc as nvarchar(max))+'0001' 

3 个答案:

答案 0 :(得分:1)

你可以缩短它......

declare @paymentid as nvarchar(50)
declare @someDate date = '2017-09-02'

set @paymentid = convert(varchar(12),@someDate,12) + '0001'
select @paymentid

答案 1 :(得分:0)

替换

set @calc = (SELECT SUBSTRING(CONVERT(char(30), '2017-09-02',112), 3, 8))   

set @calc = (SELECT SUBSTRING(CONVERT(char(30), @calc,112), 3, 8))   

答案 2 :(得分:0)

如果您有SQL Server 2012或更高版本,则可以执行以下操作:

declare 
    @now date = getdate(), -- using getdate, but you can put in a hard coded or provided date as necessary
    @paymentid nvarchar(50)

select @paymentid = format(@now, 'yyMMdd0001')

select @PaymentId --1709010001

或更简洁......

select @paymentid = format(getdate(), 'yyMMdd0001')