简体   繁体   English

在SQL Server中转换数据类型

[英]Converting data types in SQL Server

I need to change some data types. 我需要更改一些数据类型。 I have tried using the CAST keyword, but it is not fixing the issue. 我尝试使用CAST关键字,但是它不能解决问题。 Any suggestions on how to re-write these two lines with CAST statements? 关于如何使用CAST语句重新编写这两行的任何建议?

  1. Data loss might occur when casting from VarChar(100) to VarChar(20) . VarChar(100)VarChar(20)时可能会发生数据丢失。

Code: 码:

SELECT TOP 1 @variableId = variableId
FROM @tempTable
  1. Data loss might occur when casting from NVarChar(512) to NVarChar . 从铸造时可能发生数据丢失NVarChar(512)NVarChar

Code: 码:

SELECT myVariable
FROM tableName

I tried doing something like the following, but still produces an error: 我尝试执行以下操作,但仍然会产生错误:

CAST((myVariable) as nvarchar)

CAST is used for converting between data types. CAST用于在数据类型之间进行转换。 It sounds more like you should use LEFT instead: 听起来更像是应该使用LEFT代替:

SELECT TOP 1 @variableId = LEFT(variableId,20)
FROM @tempTable

This won't give you any warning as the system assumes you already know you're going to lose the right 80 characters. 这不会给您任何警告,因为系统会假设您已经知道自己将丢失正确的80个字符。

For using CONVERT instead of CAST : 对于使用CONVERT而不是CAST

CONVERT(nvarchar, myVariable)

Is a valid syntax and also: 是有效的语法,并且:

CONVERT(varchar(20), myVariable)

But for getting a part of a string we use SUBSTRING() or LEFT() or RIGHT() functions like this: 但是为了获得字符串的一部分,我们使用SUBSTRING()LEFT()RIGHT()函数,如下所示:

  • SUBSTRING( value_expression , start_expression , length_expression )

    Returns part of a character, binary, text, or image expression. 返回字符,二进制,文本或图像表达式的一部分。

  • LEFT ( character_expression , integer_expression )

    Returns the left part of a character string with the specified number of characters. 返回具有指定字符数的字符串的左侧部分。

  • RIGHT ( character_expression , integer_expression )

    Returns the right part of a character string with the specified number of characters. 返回具有指定字符数的字符串的右侧部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM