英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论