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

Time:09-23

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?

CodePudding user response:

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

CodePudding user response:

Credit to @APH, but the correct syntax is:

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

  • Related