zoukankan      html  css  js  c++  java
  • 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
    BEGIN
    	Declare @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();
                        //...
                    }
                }
            }
    
  • 相关阅读:
    HDU 4864 Task(贪心值得学习)
    使程序在Linux下后台运行
    KMP算法
    优先队列的使用
    POJ 2761 Feed the dogs(树状数组求区间第K大)
    HDU 3584 Cube (三维树状数组)
    HDU 1892 See you~ (二维树状数组)
    POJ 1195 Mobile phones(二维树状数组)
    HDU 1166 敌兵布阵 (树状数组和线段树解法)
    POj 1703 Find them, Catch them(关系并查集)
  • 原文地址:https://www.cnblogs.com/wangqilong/p/12540395.html
Copyright © 2011-2022 走看看