sp_send_dbmail - date compare in query-variable

  • Hello,

    i have the following problem in a query-variable of the internal procedure sp_send_dbmail.

    1.

    I have declared a variable like this and i have assigned a value to this variable:

    DECLARE @comparedate AS datetime

    SET @comparedate = GETDATE() - 4 (today minus 4 days)

    2.

    Now i want to use the value of this variable @comparedate as a comparison value in a query-variable which than is used as a parameter of the procedure sp_send_dbmail. For that i have built this SET Command:

    SET @abfrage='SELECT Anlagedatum, Artikel FROM S_artikel WHERE Firma = ''200'' AND Anlagedatum >=' + @comparedate + ' ORDER BY Anlagedatum'

    Here i always get this error-message:

    Meldung 241, Ebene 16, Status 1, Zeile 26

    Error converting a string into a datetime value (translated by me with from german into english Language using my very less english knowledge)

    Does anybody could help me and tell me if this can be handled like i do respectively how the select-Staement should be defined in a right way.

    Thank You very much.

    Info:

    i work on a MS SQL Server 2005 Enterprise Edition SP4.

    Thomas

  • SELECT DATEADD(HH,14,CAST(DATEADD(DD,-1,CAST(GETDATE() AS DATE)) AS DATETIME)) AS "Yesterday'sDate@2O'Clock"

  • it shoud be

    DECLARE @comparedate AS varchar(20)

    SET @comparedate = convert(varchar(20), dateadd(D,-4, GETDATE()), 102)

    declare @abfrage varchar(2050)

    SET @abfrage='SELECT Anlagedatum, Artikel FROM S_artikel WHERE Firma = ''200'' AND convert(varchar(20),Anlagedatum,102) >=''' + @comparedate + ''' ORDER BY Anlagedatum'

    if your anlagedatum is datetime type, if not then convert first to datetime

    and convert to varchar in format you want (102, 104 ...).

    be cautious when use Dynamic query from sql injection

  • This query is not for this question...Sorry;-)

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply