带插入时间的T-SQL代码段

时间:2017-02-02 23:50:28

标签: sql-server ssms code-snippets

我对MS SQL Server Management Studio中的代码段功能有疑问。我想在添加代码段时创建一个代码段,其中包含代码中某些预定义位置的当前日期和时间。并非整个脚本将被执行,因此GETDATE()将无法满足我的需求。甚至可以执行这样的任务吗?

1 个答案:

答案 0 :(得分:0)

这是SQL Server代码段中的限制。 如果您有钱,可以购买redgate sql提示或工具栏,则可以使用其更高级的代码段,这些代码段可以动态插入日期和许多其他内容。 (这些工具很棒但很昂贵)Redgate Sql Prompt Free Trial

对于我们当中的穷人,我找到了一种解决方法,方法是在我的摘要文件夹中创建一个批处理文件,并在午夜之后每天执行计划任务。它查看同一文件夹中的每个代码片段文件,并将以“-Date:XXX ...”开头的行替换为今天的日期,即。 -日期:2019年7月15日。

这意味着我的自定义代码段文件中始终写有今天的日期。

批处理文件:updatetoday.bat

:: my date environment is YYYY/MM/DD it might not be the same for you depending on your region settings
:: the script finds lines in all snippet files in the same folder as the batch file
:: starting with "-- Date:" and replaces the whole line with "-- Date: DD MMM YYYY" of the current date
:: use a scheduled task to run it each day just after midnight and it will set the date each day!

@echo off 
setlocal EnableExtensions DisableDelayedExpansion
set month=JanFebMarAprMayJunJulAugSepOctNovDec
set /a y="%date:~0,4%"
set /a m=("%date:~5,2%"-1) * 3
set /a d="%date:~8,2%"
set mn=!month:~%m%,3!
set "r=^-^- Date: %d% %mn% %y%"
for %%j in (".\*.snippet") do (
    for /f "delims=" %%i in ('type "%%~j" ^& break ^> "%%~j"') do (
        set "line=%%i"      
        setlocal EnableDelayedExpansion     
        if "!line:~0,8!" == "-- Date:" set "line=%r%"       
        >>"%%~j" echo !line!
        endlocal
    )
)
endlocal

注意:在计划的任务中,必须将“开始于”属性设置为您的代码片段文件夹。即使路径中有空格也不要使用引号。