1

I need to change some data types. I have tried using the CAST keyword, but it is not fixing the issue. Any suggestions on how to re-write these two lines with CAST statements?

  1. Data loss might occur when casting from VarChar(100) to VarChar(20).

Code:

SELECT TOP 1 @variableId = variableId
FROM @tempTable
  1. Data loss might occur when casting from NVarChar(512) to NVarChar.

Code:

SELECT myVariable
FROM tableName

I tried doing something like the following, but still produces an error:

CAST((myVariable) as nvarchar)
3
  • 2
    What is your problem? When you shorten a character string, you might lose data. That is expected and why you get the warning. Commented Jun 16, 2014 at 19:14
  • Please be more specific. What did you try? How does your data and schema looks like? The messages you provided are quite self-explaining: Your target type is to small to keep data from the source data type. Commented Jun 16, 2014 at 19:14
  • Okay, give me a minute and I will update the post! Commented Jun 16, 2014 at 19:15

2 Answers 2

2

CAST is used for converting between data types. It sounds more like you should use LEFT instead:

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.

Sign up to request clarification or add additional context in comments.

Comments

0

For using CONVERT instead of 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( 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.