如何在 C# 中声明 sql 变量

How to declare sql variable in C#

我的要求是从 table 中删除除 一条 以外的所有记录。为此,我正在执行一系列两个不同的 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. 以及,如何在单个查询字符串中执行多个查询?(如果我做对了)

编辑

我想出了这个来完成这个。但现在还是运气。请告诉我该怎么做:

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'

也许这可以帮助您,将您的查询 (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 在找不到数据时崩溃。

我的环境中 运行 正是这段代码,它按预期工作。

我的框架版本是 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();
                }
            }
        }
    }
}

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

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());
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