且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在sql中添加临时列而不创建过程

更新时间:2023-12-01 14:17:04

这是最简单的方法:

This is the simplest way:
select *, CAST('28-Dec-2008' as DATE) as fromdate, CAST('06-Apr-2013' as DATE) as todate from tblDailyMaintenceDetails where MaintenceDate between '28-Dec-2008'and '06-Apr-2013'


是 - 但您需要稍微更改您的查询。我假设你是从某种形式的语言发出这个,而不是自己直接输入SQL,在这种情况下,将开始和结束日期作为参数传递给SqlCommand(我将在C#中显示):

Yes - but you would need to change your query slightly. I assume you are issuing this from a langauge of some form, rather than entering directly into SQL yourself, in which case, pass the start and end dates as parameters to the SqlCommand (I''ll show it in C#):
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("SELECT *, @STARTDATE AS StartDate. @ENDDATE AS EndDate FROM tblDailyMaintenceDetails WHERE MaintenceDate BETWEEN @STARTDATE AND @ENDDATE", con))
        {
        com.Parameters.AddWithValue("@STARTDATE", new DateTime(2008, 12, 28));
        com.Parameters.AddWithValue("@ENDDATE", new DateTime(2013, 4, 6));
        using (SqlDataReader reader = com.ExecuteReader())
            {
            while (reader.Read())
                {
                ...
                }
            }
        }
    }

你不需要使用参数,它只是更容易在SQL的两个部分保持两个日期相同

You don''t need to use parameters, it just makes it easier to keep the two dates the same in both parts of the SQL