如何在C#中声明sql变量

时间:2015-01-22 05:37:56

标签: c# sql sql-server sql-server-2008 database-connection

我的要求是从表中删除所有记录,但一个。为此,我正在执行一系列两个不同的sql命令。好像在ssms上它运行正常,但C#不是

--This is what I run on ssms without any issue
DECLARE @int INT;
SELECT @int  =  COUNT(*) 
FROM [Table] 
WHERE STATE = 'CO';

--Delete statement
DELETE TOP (@int - 1 ) 
FROM [Table] ;

public static void ClearData(string state)
{
    const string queryToExec = @"DECLARE @int INT;" +
                               "SELECT @int  =  COUNT(*) " +
                               "FROM [Table] " +
                               "WHERE STATE = @State;" +
                               "DELETE TOP (@int - 1 ) " + //NOTICE THIS LINE
                               "FROM [Table] ";

    List<SqlParameter> param = new List<SqlParameter>()
    {
        new SqlParameter {ParameterName = "@State", SqlDbType = SqlDbType.VarChar, Value = state},
    };

    ExecQuery(queryToExec, param);
}

public static void ExecQuery(string query, List<SqlParameter> paramCollection = null)
{
    using (SqlConnection conn = new SqlConnection(ConnString))
    {
        using (SqlCommand mySqlCom = new SqlCommand())
        {
            mySqlCom.CommandText = query;
            if (paramCollection != null) mySqlCom.Parameters.AddRange(paramCollection.ToArray());
            mySqlCom.Connection = conn;
            conn.Open();
            mySqlCom.ExecuteNonQuery();
        }
    }
}

我的qsns

  1. 如何在C#中正确声明sql变量(参见 ClearData 方法)
  2. 并且,如何在单个查询字符串中执行多个查询?(如果我这样做的话)
  3. 修改

    我想出了这个来实现这个目标。但现在还好运。请告诉我该怎么做:

    IF OBJECT_ID ( 'uspWageDataByState', 'P' ) IS NOT NULL 
        DROP PROCEDURE uspWageDataByState;
    GO
    
    CREATE PROCEDURE uspWageDataByState
        @State NVARCHAR(2)  
    AS
    
        DECLARE @int INT
        SET @int  =  (SELECT COUNT(*) 
        FROM [Test] 
        WHERE [STATE] = @State)
    
        DELETE TOP (@int - 1 ) 
        FROM [Test]
        WHERE [STATE] = @State;
    
    GO
    
    exec uspWageDataByState 'CO'
    

4 个答案:

答案 0 :(得分:3)

我在我的环境中运行了这个代码,它正在按预期工作。

我的框架版本是4.5.51641,我的SQL版本是SQL Server 11.0.2100

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;

namespace PruebasSQL
{
    class Program
    {
        const string ConnString = @"";

        static void Main(string[] args)
        {
            ClearData("A");
        }

        public static void ClearData(string state)
        {
            const string queryToExec = @"DECLARE @int INT;" +
                                       "SELECT @int  =  COUNT(*) " +
                                       "FROM [Table] " +
                                       "WHERE STATE = @State;" +
                                       "DELETE TOP (@int - 1 ) " + //NOTICE THIS LINE
                                       "FROM [Table] ";

            List<SqlParameter> param = new List<SqlParameter>()
            {
                new SqlParameter {ParameterName = "@State", SqlDbType = SqlDbType.VarChar, Value = state},
            };

            ExecQuery(queryToExec, param);
        }

        public static void ExecQuery(string query, List<SqlParameter> paramCollection = null)
        {
            using (SqlConnection conn = new SqlConnection(ConnString))
            {
                using (SqlCommand mySqlCom = new SqlCommand())
                {
                    mySqlCom.CommandText = query;
                    if (paramCollection != null) mySqlCom.Parameters.AddRange(paramCollection.ToArray());
                    mySqlCom.Connection = conn;
                    conn.Open();
                    mySqlCom.ExecuteNonQuery();
                }
            }
        }
    }
}

答案 1 :(得分:1)

也许这可以帮助您,使用:

更改您的查询(queryToExec)
ALTER PROCEDURE uspWageDataByState
@State NVARCHAR(2)  
AS

DELETE TOP 
(CASE 
    (SELECT COUNT(*) FROM [Test] WHERE [STATE] = @State) 
    WHEN 0 THEN 1 
    ELSE (SELECT COUNT(*) FROM [Test] WHERE [STATE] = @State) END -1) 
FROM [Test]
WHERE [STATE] = @State;

如果声明的变量是你可以解决的问题,那不是最好的查询,但是你使用的不是最好的形式:P。

我正在添加0行验证,换句话说,当没有找到数据时,sp崩溃了。

答案 2 :(得分:0)

在单个字符串语句中执行多个查询:

string querystring = "select [yourcolumns] from [yourtable];select [yourvalues] from [yourtables]";
sqlcommand cmd  = new sqlcommand(querystring,yourconnection);
sqlDataReader reader = cmd.executeReader();
do
{
 while(reader.Read())
{
 //get your values here
}
}while(reader.NextResult());

答案 3 :(得分:0)

DECLARE @PageSize INT = 5, @PageNum   INT = 1
SELECT tickets.ID, tickets.userID FROM tickets WHERE tickets.isActive = 1
OFFSET (@PageNum-1)*@PageSize ROWS FETCH NEXT @PageSize ROWS ONLY

以这种方式在 aspnet sqlcommanddatareader 中工作