Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't this SQL CAST work? [closed]

I have a nvarchar(50) column in a SQL Server 2000 table defined as follows:

TaskID nvarchar(50) NULL

I need to populate this column with random SQL GUID's using the NEWID() function (I am unable to change the column type to uniqueidentifier).

I tried this:

UPDATE TaskData SET TaskID = CAST(NEWID() AS nvarchar)

but I got the following error:

Msg 8115, Level 16, State 2, Line 1 Arithmetic overflow error converting expression to data type nvarchar.

I also tried:

UPDATE TaskData SET TaskID = CAST(NEWID() AS nvarchar(50))

but then got this error:

Msg 8152, Level 16, State 6, Line 1 String or binary data would be truncated.

I don't understand why this doesn't work but this does:

DECLARE @TaskID nvarchar(50)
SET @TaskID = CAST(NEW() AS nvarchar(50))

I also tried CONVERT(nvarchar, NEWID()) and CONVERT(nvarchar(50), NEWID()) but got the same errors.

Update:

Ok, my eyesight is going, the column size on the table is nvarchar(32) not 50. Deepest apologies for the timewasting and thanks for all the answers.

like image 943
Kev Avatar asked Mar 16 '10 16:03

Kev


People also ask

What can be used instead of CAST in SQL?

Both CAST and CONVERT are functions used to convert one data type to another data type. It is mainly used in the Microsoft SQL program, and both are often used interchangeably.

How does CAST work in SQL?

In SQL Server (Transact-SQL), the CAST function converts an expression from one datatype to another datatype. If the conversion fails, the function will return an error. Otherwise, it will return the converted value. TIP: Use the TRY_CAST function to return a NULL (instead of an error) if the conversion fails.

What is CAST () and convert () functions in SQL Server?

The cast and convert functions provide similar functionality. They are used to convert a value from one data type to another. So let's take a look at a practical example. The example is developed in SQL Server 2012 using the SQL Server Management Studio.

What is the difference between CAST and convert in SQL?

CAST is part of the ANSI-SQL specification; whereas, CONVERT is not. In fact, CONVERT is SQL implementation-specific. CONVERT differences lie in that it accepts an optional style parameter that is used for formatting.


2 Answers

This test script works fine for me... I can only suggest that maybe your TaskId isn't an NVARCHAR(50) like you say? Try an sp_columns just to check...

CREATE Table #TaskData (TaskId NVARCHAR(50))
INSERT INTO #TaskData (TaskId) SELECT CONVERT(NVARCHAR(50), NEWID())
UPDATE #TaskData SET TaskId = CONVERT(NVARCHAR(50), NEWID())
DROP TABLE #TaskData
like image 195
Robin Day Avatar answered Oct 11 '22 19:10

Robin Day


Please try the following cast:

CAST(NEWID() AS varchar(255))
like image 27
Arnkrishn Avatar answered Oct 11 '22 20:10

Arnkrishn