简体   繁体   English

如何在sql server中将GETDATE(仅限日期)作为参数传递?

[英]How to pass GETDATE (Only date) as a parameter in sql server?

I want to pass the system date ( GETDATE ) only as a parameter in my SQL stored procedure.我只想将系统日期 ( GETDATE ) 作为参数传递给我的 SQL 存储过程。 But I am getting an error while executing the procedure.但是我在执行程序时遇到错误。

SQL query: SQL查询:

  ALTER PROCEDURE ST_PRO_GETUSER
  @D DATETIME = GETDATE  --// passing GETDATE as a parameter.
  AS BEGIN
    select case when branch in ('A25','B10','C10')  
    then 'BR B1' Else 'BR B2' 
    end As [COLLECTION],FIXDATE 
    from MAIN_COUNTER where TDATE=@D  --//Just want to pass date only
    group by COLLECTION,FIXDATE 
 END

 EXEC KK_SP_GETUSER_DIV

Error:错误:

Conversion failed when converting date and/or time from character string.从字符串转换日期和/或时间时转换失败。

What I have to do for it?我必须为它做什么?

To pass as a parameter you just declare a variable and pass it in:要作为参数传递,您只需声明一个变量并将其传入:

DECLARE @DATE DATETIME = GETDATE();
EXEC ST_PRO_GETUSER @DATE;

And if you want the date only, change the datatype of your parameter to a date and then do:如果您只想要日期,请将参数的数据类型更改为date ,然后执行以下操作:

DECLARE @DATE DATE = GETDATE();
EXEC ST_PRO_GETUSER @DATE;

But part of your question seems to actually be asking how to specify a default parameter value.但是您的部分问题似乎实际上是在询问如何指定默认参数值。 You can't use a function for the default value, so instead do:您不能将函数用于默认值,因此请执行以下操作:

CREATE PROCEDURE ST_PRO_GETUSER
(
    @Date DATETIME = null
    -- Change to DATE datatype if you don't want a time component.
    -- @Date DATE = null
)
AS
BEGIN
    SET NOCOUNT ON;

    -- Default the @Date here is its null.
    -- Note this doesn't handle the case when the caller wants to pass in null.
    SET @Date = COALESCE(@Date,GETDATE());

    -- SP Body

    RETURN 0;
END

Solved My Self解决了我的自我

     ALTER PROCEDURE ST_PRO_GETUSER
     @Date datetime = null
     as
     IF @Date is null
     SET @Date = getdate()  --// passing GETDATE as a parameter.
      BEGIN
       select case when branch in ('A25','B10','C10')  
       then 'BR B1' Else 'BR B2' 
       end As [COLLECTION],FIXDATE 
       from MAIN_COUNTER where TDATE=@D  --//Just want to pass date only
       group by COLLECTION,FIXDATE 
     END

EXEC ST_PRO_GETUSER

GETDATE()是正确的语法,而不是GETDATE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM