在C#中的SQL语句中使用局部变量值

时间:2017-04-28 09:21:03

标签: c# sql sql-server

我试图在

中的sql atatement中动态地从日期中减去天数
C# code I have is
int myInt=6;       //its value will vary
  var q = SELECT [DATE] FROM DB WHERE  [Date ] < DATEADD(dd, **myint**, GETDATE())";

有没有办法在sql语句中传递这个变量?

我试过这个

 var q = SELECT [DATE] FROM DB WHERE  [Date ] < DATEADD(dd, [coumln]+"'+myint+'", GETDATE())";

1 个答案:

答案 0 :(得分:6)

确实,您应该将此作为参数传递;

string connectionString = "YourConnectionString";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand(
                "SELECT [DATE] FROM DB WHERE [Date] < DATEADD(dd, @MyInt, GETDATE())", connection))
            {                    
                command.Parameters.Add(new SqlParameter("MyInt", myInt));
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    DateTime date = reader.GetDateTime(0);
                    Console.WriteLine("Date: {0}",
                        date);
                }
            }
        }

你也可以使用像LinqToSql这样的东西:https://msdn.microsoft.com/en-us/library/bb425822.aspx 或像Dapper这样的ORM:https://github.com/StackExchange/Dapper