Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Interesting difference in CAST vs CONVERT functions
Message
 
 
À
Tous
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Syntaxe SQL
Titre:
Interesting difference in CAST vs CONVERT functions
Versions des environnements
SQL Server:
SQL Server 2005
Divers
Thread ID:
01294297
Message ID:
01294297
Vues:
59
Hi everybody,

We found an interesting and not intuitive behavior of the CAST function.

The following sample code produces an error:
CREATE DATABASE Test
GO
USE Test
GO
Create TABLE Test1 (Fld1 int, Fld2 varchar(200)
CONSTRAINT PK_Tets1
    PRIMARY KEY CLUSTERED (Fld1)
)

Create TABLE Test2 (Fld1 int, Fld2 int, Fld3 int, Fld4 varchar(200))
CREATE INDEX IX_Test2 ON Test2 (Fld1, Fld2, Fld3)
GO

declare @counter int
set @counter = 1
while @counter < 100000 
  begin
	  insert into Test1 values (@counter, 'Counter' + cast(@counter as char(10))

	  insert into Test2 values (@counter, @counter, @counter,'Counter' + cast(@counter as varchar(10))

	  set @counter = @counter +1
end

Using Convert function works as expected:
declare @counter int
set @counter = 1
while @counter < 100000 
  begin
	  insert into Test1 values (@counter, 'Counter ' + convert(varchar(10),@counter))
	  insert into Test2 values (@counter, @counter, @counter,'Counter' + convert(varchar(10),@counter))
	  set @counter = @counter +1
  end
So, it looks like the CAST() function actually changes the type of the variable.

BTW, what SQL Server function would tell us the TYPE of the variable/field?
If it's not broken, fix it until it is.


My Blog
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform