DataAdd日期部分varchar

时间:2018-06-01 15:43:14

标签: sql-server

我有一个查询,我从一个长字符串中动态获取一个频率,并希望将它放入一个DateAdd函数中。我知道,第一个参数预期日期等将不允许变量,并期望系统不变。我有什么办法可以创造出来吗?一个常量或者我是否必须修改我的sql以适应case语句中的多个DateAdd函数..这是选择日期部分的case语句..

Select DateAdd(cast
(
    CASE 
        CASE WHEN PATINDEX('%Type="%', RecurrenceInfo) <> 0 
            THEN SUBSTRING(RecurrenceInfo, PATINDEX('%Type="%', RecurrenceInfo) + 6, 1) 
            ELSE NULL END 
        WHEN '0' THEN 'Day' 
        WHEN '1' THEN 'Week' 
        WHEN '2' THEN 'Month' 
        WHEN '3' THEN 'Year' 
        ELSE NULL 
        END as varchar(5)
),5, MyDate)

2 个答案:

答案 0 :(得分:2)

只需使用您已有的案例并跳过投射

Select 
(
    CASE 
        CASE WHEN PATINDEX('%Type="%', RecurrenceInfo) <> 0 
            THEN SUBSTRING(RecurrenceInfo, PATINDEX('%Type="%', RecurrenceInfo) + 6, 1) 
            ELSE NULL END 
        WHEN '0' THEN DateAdd(day, 5, MyDate) 
        WHEN '1' THEN DateAdd(week, 5, MyDate)
        WHEN '2' THEN DateAdd(month, 5, MyDate)
        WHEN '3' THEN DateAdd(year, 5, MyDate)
        ELSE NULL 
        END 
)

答案 1 :(得分:0)

从评论中听起来你不确定动态SQL解决方案会是什么样子,所以我想我会在这里发布它是为了完整性。我实际上并不建议你使用这个答案 - JamieD77更好 - 但这至少证明了这种技术,以防你将来遇到一个使用动态SQL的情况确实值得麻烦的情况。

-- Since I don't have the full context of your original query, I'm just going to use
-- local variables for RecurrenceInfo and MyDate.
declare @RecurrenceInfo varchar(128) = 'Type="2"';
declare @MyDate date = convert(date, getdate());

-- Here is basically the CASE you had in your question, used to assign the value of
-- another variable rather than to evaluate the DATEADD expression directly.
declare @DatePart nvarchar(5) =
    CASE 
        CASE WHEN PATINDEX('%Type="%', @RecurrenceInfo) <> 0 
            THEN SUBSTRING(@RecurrenceInfo, PATINDEX('%Type="%', @RecurrenceInfo) + 6, 1)
            ELSE NULL END 
        WHEN '0' THEN 'Day' 
        WHEN '1' THEN 'Week' 
        WHEN '2' THEN 'Month' 
        WHEN '3' THEN 'Year' 
        ELSE NULL 
    END;

-- And here's an example of building dynamic SQL. Given the sample data used above,
-- the @Sql variable will hold the following string:
--
--     select dateadd(Month, @Increment, @MyDate);
--
-- I then pass that query to sp_executesql along with some proper parameters for the
-- other two inputs required by DATEADD.
declare @Sql nvarchar(max) = N'select dateadd(' + @DatePart + N', @Increment, @MyDate);';
if @Sql is not null
    exec sp_executesql @Sql, N'@Increment int, @MyDate date', @Increment = 5, @MyDate = @MyDate;
else
    select null;

在适当的情况下,这是一项功能强大的技术,但在这种情况下,增加太多的复杂性可能会增加太多。如果您确实开始使用动态SQL,请务必阅读SQL injection