我有下表名为Fruits。
ID English Spanish German
1 Apple Applice Apple-
2 Orange -- --
如果程序通过1和英语,我必须返回'Apple'。我怎么能写那个sql查询?谢谢。
答案 0 :(得分:5)
select
ID,
case @Lang
when 'English' then English
when 'Spanish' then Spanish
end as Name
from Fruits
where ID = @ID;
或者,如果您有多个列可供选择,您可以使用apply,这样您就不必编写多个案例陈述
select
F.ID,
N.Name,
N.Name_Full
from Fruits as F
outer apply (values
('English', F.English, F.English_Full),
('Spanish', F.Spanish, F.Spanish_Full)
) as N(lang, Name, Name_Full)
where F.ID = @ID and N.lang = @lang
答案 1 :(得分:2)
Fisrt你应该规范化数据库,支持多语言,这意味着将表拆分为2
表格:
Fruit
(FruitID, GenericName 等)Languages
(LanguageID,LanguageName等)FruitTranslations
(FruitID,LanguageID,LocalizedName)然后查询将只是对表FruitTranslations的简单查询...
如果您仍然想要查询,那么您可以使用动态SQL,
DECLARE @cmd VARCHAR(MAX)
SET @Cmd = 'SELECT ' + @Language +
' FROM Fruits WHERE ID = ''' + CONVERT(VARCHAR, @Id) + ''''
EXEC(@Cmd)
答案 2 :(得分:2)
试试这个 -
DECLARE
@Lang VARCHAR(10) = 'English'
, @ID INT = 1
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = '
SELECT ' + @Lang + '
FROM dbo.Fruits
WHERE ID = ' + CAST(@ID AS VARCHAR(4))
PRINT @SQL
EXEC sys.sp_executesql @SQL
答案 3 :(得分:0)
您可以使用存储过程来执行此操作,因为在存储过程中您可以使用“if else”条件。例如:
@ID as int,@Lang as varchar(50)
if @Lang = 'English'
begin
select ID,English from Fruits where ID = @ID;
end
else
if @Lang = 'Spanish'
begin
select ID,Spanish from Fruits where ID = @ID;
end
...