存储过程动态sql拼接
时间: 2023-11-04 17:06:05
浏览: 62
在存储过程中,我们可以使用[动态](https://geek.csdn.net/educolumn/08aef4ab97997f5b9ed71860c44e8258?spm=1055.2569.3001.10083) SQL 拼接来构建[动态](https://geek.csdn.net/educolumn/08aef4ab97997f5b9ed71860c44e8258?spm=1055.2569.3001.10083)查询语句。[动态](https://geek.csdn.net/educolumn/08aef4ab97997f5b9ed71860c44e8258?spm=1055.2569.3001.10083) SQL 拼接可以让我们根据不同的条件,[动态](https://geek.csdn.net/educolumn/08aef4ab97997f5b9ed71860c44e8258?spm=1055.2569.3001.10083)地构建 SQL 语句,从而实现更加灵活和可扩展的查询。
以下是一个使用[动态](https://geek.csdn.net/educolumn/08aef4ab97997f5b9ed71860c44e8258?spm=1055.2569.3001.10083) SQL 拼接的示例:
CREATE PROCEDURE dynamic_search
@name VARCHAR(50) = NULL,
@min_age INT = NULL,
@max_age INT = NULL
BEGIN
SET NOCOUNT ON;
DECLARE @sql NVARCHAR(MAX) = 'SELECT * FROM users WHERE 1 = 1';
IF (@name IS NOT NULL)
BEGIN
SET @sql = @sql + ' AND name LIKE ''' + @name + '%''';
IF (@min_age IS NOT NULL)
BEGIN
SET @sql = @sql + ' AND age >= ' + CAST(@min_age AS VARCHAR(10));
IF (@max_age IS NOT NULL)
BEGIN
SET @sql = @sql + ' AND age <= ' + CAST(@max_age AS VARCHAR(10));
EXEC sp_executesql @
```