我正在研究SQL Server 2012脚本,我需要像这样做逻辑;
如果ans.value是UNIQUEIDENTIFIER / Guid,那么从xtable中选择值(字符串),其中xtable.value = ans.value else ans.value(ans.value将是字符串或空)
这是我已经取得的成就......
SELECT
ans.Id,
calculatedVal = ISNULL(TRY_CONVERT(UNIQUEIDENTIFIER, ans.Value), 'select from xtable....') ?????
FROM [Answers] AS ans
所以基本上我需要执行sql select并将字符串值赋给' calculatedVal'如果TRY_CONVERT(UNIQUEIDENTIFIER,ans.Value)不是NULL ...我怎么能这样做
答案 0 :(得分:2)
您可以使用CASE
:
SELECT
ans.Id,
CASE WHEN TRY_CONVERT(UNIQUEIDENTIFIER, ans.Value) IS NOT NULL THEN
(select TOP 1 col_name from xtable WHERE ... ORDER BY ...)
ELSE ans.Value
END AS calculatedVal
FROM [Answers] AS ans;
或使用IIF
SELECT
ans.Id,
IIF(TRY_CONVERT(UNIQUEIDENTIFIER, ans.Value) IS NOT NULL,
(select TOP 1 col_name from xtable WHERE ... ORDER BY ...)
,ans.Value)AS calculatedVal
FROM [Answers] AS ans;