SQL Server 动态SQL拼接

编程入门 行业动态 更新时间:2024-10-27 10:18:08

SQL Server <a href=https://www.elefans.com/category/jswz/34/1771299.html style=动态SQL拼接"/>

SQL Server 动态SQL拼接

在多选项综合搜索数据时,大多会使用到动态SQL搜索,当搜索栏目中存在string,Guid,decimal等类型数据时,要注意拼接时数据类型转换,方法如下:

方法一:使用 SQL Server中的存储过程(StoredProcedure),在存储过程中拼接SQL,SQL拼接的语句为字符串,当我们去拼接Guid等特殊类型时就需要去转换成字符串,如果直接拼接,SQL会直接报错。
具体如下:

ALTER PROCEDURE [dbo].[GetProductList]
(@ProductID uniqueidentifier,@Price decimal(18, 2),@Description varchar(max)
)
AS
BEGINDeclare @strSql varchar(max);--SQL拼接SET @strSql='SELECT ProductID,Name,Price,Description FROM [test].[dbo].[Product] WHERE 1=1'IF(@ProductID is not null)begin SET @strSql=@strSql+' AND ProductID= ''' +convert(varchar(36),@ProductID)+ ''''    --Guid类型转换end  IF(@Description!='')begin SET @strSql=@strSql+' AND Description like ''%'+@Description+'%'''end EXEC(@strSql)
END

方法二:直接在后台代码中,拼接SQL后,去执行SQL
具体如下:

public static void SQLFunction(Product product) {//SQL拼接string sql = "SELECT ProductID,Name,Price,Description FROM [test].[dbo].[Product] WHERE 1=1";if (product.ProductID!=null) {sql = sql + " AND ProductID='"+ product.ProductID + "'";}if (product.Description != "") {sql = sql + " AND Description like '%" + product.Description + "%'";}using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnection"].ConnectionString))using (SqlCommand cmd = new SqlCommand()){cmd.CommandType = CommandType.Text;            cmd.CommandText = sql;cmd.Connection = conn;conn.Open();SqlDataReader reader = cmd.ExecuteReader();while (reader.Read()){Product pro = new Product();                   pro.Description = reader["Description"].ToString();//...}}}

更多推荐

SQL Server 动态SQL拼接

本文发布于:2024-02-11 07:27:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1679831.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:动态   SQL   Server

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!