You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何执行带参数的SQL查询(使用LIKE与@变量)?LIKE语法与%位置咨询

Hey there! Let’s tackle these two SQL questions one by one—they’re super common, so I’ll use concrete examples to make it clear.

1. 执行带参数的SQL查询(使用LIKE运算符与@变量)

When working with @variables (common in SQL Server, Azure SQL, etc.), the key is to keep your query parameterized (to avoid SQL injection) while integrating the LIKE operator. Here’s how to do it right:

Example for SQL Server:

First, declare your variable, then use it in the LIKE clause by combining it with wildcard characters (%) using string concatenation or the CONCAT function:

-- Declare and set your parameter value
DECLARE @SearchKeyword NVARCHAR(50) = 'doe';

-- Option 1: Using string concatenation
SELECT FirstName, LastName, Email
FROM Users
WHERE LastName LIKE '%' + @SearchKeyword + '%';

-- Option 2: Using CONCAT (cleaner, works with NULL values)
SELECT FirstName, LastName, Email
FROM Users
WHERE LastName LIKE CONCAT('%', @SearchKeyword, '%');

If you’re using this in an application (like C#/Java/Python), you’d pass the @SearchKeyword as a parameter to your command object instead of hardcoding it—this is critical for security.

2. 基于用户输入执行SELECT查询时,LIKE的正确语法与通配符%的位置

The position of the % wildcard depends on what you want to match, but always use parameterized queries when dealing with user input (never directly insert user input into your SQL string—this is a huge SQL injection risk).

Here’s how the wildcard positions work:

  • Match strings ending with the input: Place % at the start of the pattern
    -- Matches "JohnDoe", "JaneDoe", etc.
    SELECT * FROM Users WHERE LastName LIKE '%' + @UserInput + '';
    
  • Match strings starting with the input: Place % at the end of the pattern
    -- Matches "DoeJohn", "DoeJane", etc.
    SELECT * FROM Users WHERE LastName LIKE '' + @UserInput + '%';
    
  • Match strings containing the input anywhere: Place % on both sides
    -- Matches "JohnDoe", "DoeJane", "JohnDoeSmith", etc.
    SELECT * FROM Users WHERE LastName LIKE '%' + @UserInput + '%';
    

Critical Note:

Avoid this dangerous practice at all costs:

-- ❌ RISKY: Directly concatenates user input (SQL injection vulnerability!)
SELECT * FROM Users WHERE LastName LIKE '%' + 'UserInputFromForm' + '%';

Always use parameterized variables (like @UserInput) to separate user data from your SQL logic.

内容的提问来源于stack exchange,提问作者Sema

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:58:32