SQL中如何实现类似JavaScript模板字符串的查询拼接?
SQL中实现类似JavaScript模板字符串的变量拼接功能
你的原始代码如下:
declare @num int set @num = (SELECT Id FROM [sometable] WHERE Name like '%today%') -- returns @num = 1 Select Value FROM [anothertable] where name like 'days1'
要实现根据@num的值动态拼接'days'后的数字,在SQL(以SQL Server为例)里可以用以下几种方式:
使用
+运算符拼接
由于@num是整数类型,需要先转换为字符串,可借助CAST或CONVERT函数:Select Value FROM [anothertable] where name = 'days' + CAST(@num AS VARCHAR(10)) -- 若需模糊匹配,比如匹配以拼接结果开头的内容,可改为: -- where name LIKE 'days' + CAST(@num AS VARCHAR(10)) + '%'使用
CONCAT函数(SQL Server 2012及以上版本支持)CONCAT会自动处理不同数据类型的转换,无需手动转类型,写法更简洁:Select Value FROM [anothertable] where name = CONCAT('days', @num) -- 模糊匹配写法: -- where name LIKE CONCAT('days', @num, '%')使用
STRING_FORMAT函数(SQL Server 2012及以上版本支持)
这个函数的语法最接近JavaScript的模板字符串${},可以通过占位符动态插入变量:Select Value FROM [anothertable] where name = STRING_FORMAT('days{0}', @num)
内容的提问来源于stack exchange,提问作者CK Vignesh
相关产品推荐
相关产品推荐

