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

Viewed 318

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?

2 Answers

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

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)

Related