Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
895 views
in Technique[技术] by (71.8m points)

sql server - About 'CASE' a conversion failure

While using 'CASE' I encountered with problem that I'D never heard.
The problem is so: I'M using 'CASE' statement in 'SELECT' clause as a field. When calling columns with int data type, it's successful; However, When calling a varchar or datetime, it's unsuccessful.
?n the error result, it's said me to have marked the temporary field, including 'CASE' statement, as int, But not so. Please help...

The 'STORED PROCEDURE' Content

CREATE PROC spRegistry_PersonsGetField
@ID int,
@Field varchar(100)
AS
SELECT CASE @Field 
WHEN 'Name' THEN Name
WHEN 'Surname' THEN Surname
WHEN 'Username' THEN Username
WHEN 'Password' THEN Password
WHEN 'Status' THEN dbo.fnStatus(Status)
WHEN 'EMail' THEN EMail
WHEN 'Tel' THEN dbo.fnIsEmpty(Tel)
WHEN 'Address' THEN dbo.fnIsEmpty(Address)
WHEN 'City' THEN dbo.fnIsEmpty(City)
WHEN 'BirthDate' THEN dbo.fnDate(BirthDate)
WHEN 'Gender' THEN dbo.fnGender(Gender)
WHEN 'Lang' THEN Lang
ELSE NULL
END
AS [Alan] varchar(200)
FROM Registry_Persons
WHERE ID = @ID

My Query

EXEC spRegistry_PersonsGetField 1, 'BirthDate'

The Error Message

Conversion failed when converting the varchar value '04/11/2011' to data type int.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

T-SQL's Precedence rules apply when a CASE is evaluated in order to work out what the single returned datatype is to be. Since int has a higher precedence than varchar an implicit conversion to int is attempted & subsequently fails.

To fix this, convert your int or datetime expressions to varchar.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...