在Go语言中使用MSSQL的Select查询中,如何使用LIKE和%通配符?

huangapple go评论85阅读模式
英文:

How do I use LIKE with % in a Select Query in Go for MSSQL?

问题

我想使用%在SQL数据库中使用LIKE来获取记录列表。我正在使用github.com/denisenkom/go-mssqldb包。我的查询目前如下:

row, err := DB.Query("SELECT * FROM Person WHERE Name LIKE %@p1%", nameToSearch)

这会抛出错误:Incorrect syntax near '@p1'.

我尝试了其他查询的变体,包括以下内容:

  • SELECT * FROM Person WHERE Name LIKE '%%' @p1 '%%'
  • SELECT * FROM Person WHERE Name LIKE '%%' || @p1 || '%%'
    这些也失败了。

我使用的驱动程序是否无法支持带有通配符的LIKE操作?

英文:

I want to get a list of records from a SQL database using LIKE with % before and after the search term. I'm using the github.com/denisenkom/go-mssqldb package. My query is as follows currently:

row, err := DB.Query("SELECT * FROM Person WHERE Name LIKE %@p1%", nameToSearch)

This throws the error: Incorrect syntax near '@p1'.

I've tried other variations of the query including the following:

  • SELECT * FROM Person WHERE Name LIKE '%%' @p1 '%%'
  • SELECT * FROM Person WHERE Name LIKE '%%' || @p1 || '%%'
    These fail as well.

Is the driver I'm using not able to support Like's with wildcards?

答案1

得分: 2

为了完整性/防止注释丢失 - 在T-SQL/MS SQL中,使用变量作为通配符的语法如下:

DECLARE @p1 VARCHAR(10) = 'test' --声明并设置变量

print '%' + @p1 + '%' --例如,查看连接(对于下面的代码不是必需的)
print '%@p1%' --与将@p1视为字符串而不是变量的不正确语法进行比较

SELECT * FROM MyTable WHERE Column LIKE '%' + @p1 + '%' --通配符条件的正确语法
英文:

For completeness/in case comments are lost - in T-SQL/MS SQL, the syntax to use a variable as a wildcard is:

DECLARE @p1 VARCHAR(10) = 'test' --declare and set variable

print '%' + @p1 + '%' --for example to see concatenation (not necessary for code below)
print '%@p1%' --compared to incorrect syntax treating @p1 as a string rather than a variable

SELECT * FROM MyTable WHERE Column LIKE '%' + @p1 + '%' --correct syntax for wildcard criteria

答案2

得分: 0

感谢 @APH,但在 GO 代码中的正确语法是:

row, err := DB.Query("SELECT * FROM wsd.CUSMASFL WHERE CMNAME LIKE '%' + @p1 + '%'", nameToSearch)

英文:

Credit to @APH, but the correct syntax within the GO code is:

row, err := DB.Query("SELECT * FROM wsd.CUSMASFL WHERE CMNAME LIKE '%' + @p1 + '%'", nameToSearch)

huangapple
  • 本文由 发表于 2021年9月23日 01:58:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/69289160.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定