[英]T-SQL: Execute command in case block
Is there any possible way to execute something like this in T-SQL? 有没有可能在T-SQL中执行类似的事情?
CASE @@VERSION
WHEN 'SQL Server 2005'
THEN Command_A
ELSE Command_B
END
This case block should pick Command_A if the server version is 2005. If not Command_B should get executed. 如果服务器版本为2005,则此case块应选择Command_A。否则请选择Command_B。
Actually the case is a "subcommand" of SELECT you could achieve what you want with something like this: 实际上,情况是SELECT的“子命令”,您可以通过以下方式实现所需的功能:
declare @s varchar(255)
select @s = case @@VERSION
when 'SQL Server 2005'
THEN 'command 1'
ELSE 'command 2'
END
exec (@s)
That should work just fine, like this: 这样应该可以正常工作,如下所示:
if (@@version like '%SQL Server 2014%') select '2014'
else select 'Other'
See SQL Fiddle . 请参见SQL Fiddle 。
But if you're going to have there code that is not supported by the version you're running it in, you should either create separate procedures that you're going to call, or use dynamic SQL. 但是,如果要运行的版本不支持该代码,则应创建要调用的单独过程,或使用动态SQL。
You can use dynamic SQL for that 您可以为此使用动态SQL
DECLARE @dynamicSql VARCHAR(max);
CASE @@VERSION
WHEN 'SQL Server 2005'
THEN @dynamicSql = 'Command_A'
ELSE @dynamicSql = 'Command_B'
END
EXEC (@dynamicSql)
You can use this CASE
to get the sql-server version: 您可以使用此
CASE
获取sql-server版本:
SELECT CASE SUBSTRING(CAST(SERVERPROPERTY('productversion')AS nvarchar(128)), 1, CHARINDEX('.', CAST(SERVERPROPERTY('productversion')AS nvarchar(128))) - 1)
WHEN 7 THEN 'SQL Server 7'
WHEN 8 THEN 'SQL Server 2000'
WHEN 9 THEN 'SQL Server 2005'
WHEN 10 THEN 'SQL Server 2008/2008 R2'
WHEN 11 THEN 'SQL Server 2012'
WHEN 12 THEN 'SQL Server 2014'
ELSE 'Unsupported' END AS DB_Version
Then you just need to execute dynamic sql according to the result. 然后,您只需要根据结果执行动态sql。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.