我正在尝试将日期字段和数字字段合并到我的查询中 - 我需要将日期显示为带有序列号的数字。
我试过了
SELECT CAST(movement_date AS int) + CAST(sequence_no AS int) AS MOVE
这给出了日期为03/11/2015的结果42312和序列号000003.但是我需要42309000003的结果 - 所以日期和序列连接为INT而不是添加。
答案 0 :(得分:1)
你需要将它像一个字符串一样附加到:
SELECT CAST(CAST(movement_date AS int) as varchar(5)) + CAST(CAST(sequence_no AS int) as varchar(6)) AS MOVE
修改强>
SELECT (CAST(CAST(movement_date AS int) as varchar(5)) +
RIGHT('00000'+ CAST(CAST(sequence_no AS int) as varchar(6)),6)) AS [MOVE]
或者您可以使用REPLICATE填充所需数量的0,如下所示:
SELECT CAST(CAST(movement_date AS int) as varchar(5)) + REPLICATE('0',6-LEN(CAST(CAST(sequence_no AS int) as varchar(6)))) AS [MOVE]
答案 1 :(得分:1)
这就是你应该怎么做的。
SELECT
{fn concat(CAST(CAST(movement_date AS int) AS varchar), CAST(CAST(sequence_no AS int) AS varchar))} AS MOVE FROM table_name
或
SELECT
CONCAT(CAST(CAST(movement_date AS int) AS varchar), CAST(CAST(sequence_no AS int) AS varchar)) AS MOVE FROM table_name
如果您仍想选择int或任何其他数字类型,则只需将所有内容封装到CAST(值AS anyNumberType)。
编辑: 如果要在“sequence_no”中保留前导零,则不应将CAST作为int,因为这是删除前导零的位置。只是投入其他东西(可能是varchar)。
SELECT
{fn concat(CAST(CAST(movement_date AS int) AS varchar), CAST(sequence_no AS varchar))} AS MOVE FROM table_name
或
SELECT
CONCAT(CAST(CAST(movement_date AS int) AS varchar), CAST(sequence_no AS varchar)) AS MOVE FROM table_name
此外,您可以使用“+”符号来连接非数字值,但我更喜欢函数:)
答案 2 :(得分:1)
SELECT CAST(movement_date AS int) + CAST(sequence_no AS int) AS MOVE
如果要使用sequence_no附加movemen_date,则不要将它们强制转换为int。
Cast tem as nvarchar.
SELECT CAST(movement_date AS nvarchar(max)) + CAST(sequence_no AS nvarchar(max)) AS MOVE