I have created a procedure with this structure but it doesn’t work for datetime input parameter
I executed this query but
declare @a datetime
declare @b datetime
set @a='2012/04/06 12:23:45'
set @b='2012/08/06 21:10:12'
exec LogProcedure 'AccountLog', N'test', @a, @b
but SQL Server got me this error
Conversion failed when converting date and/or time from character string.
but when I test with this query it works
exec LogProcedure 'AccountLog',N'test'
Stored procedure code:
alter PROCEDURE LogProcedure
@TableName VARCHAR(60),
@SearchString NVARCHAR(50),
@DateFirst DateTime = '',
@DateLast DateTime = ''
AS
BEGIN
SET NOCOUNT ON
DECLARE @FinalSQL NVARCHAR(MAX)
SET @FINALSQL = 'SELECT * FROM [' + @TableName + '] where 1=2 '
IF @DateFirst <> '' and @DateLast <> ''
set @FinalSQL = @FinalSQL + ' or convert (Date,DateLog) >= '''+@DateFirst + ' and convert (Date,DateLog) <='''+@DateLast
SELECT
@FinalSQL = @FinalSQL + ' or [' + SYSCOLUMNS.NAME + '] LIKE N''%' + @SearchString + '%'' '
FROM SYSCOLUMNS
WHERE OBJECT_NAME(id) = @TableName
AND TYPE_NAME(SYSCOLUMNS.XTYPE) IN ('VARCHAR','NVARCHAR','CHAR','NCHAR','INT','DECIMAL')
ORDER BY COLID
EXEC(@FinalSQL)
END
This query is true too
SELECT *
FROM AccountLog
where 1=2 or convert (Date, DateLog) >= '2012/04/06'
and convert (Date, DateLog) <='2012/08/06'
You should use the ISO-8601 format for string representations of dates – anything else is dependent on the SQL Server language and dateformat settings.
The ISO-8601 format for a
DATETIMEwhen using only the date is:YYYYMMDD(no dashes or antyhing!)For a
DATETIMEwith the time portion, it’sYYYY-MM-DDTHH:MM:SS(with dashes, and aTin the middle to separate date and time portions).If you want to convert a string to a
DATEfor SQL Server 2008 or newer, you can useYYYY-MM-DD(with the dashes) to achieve the same result. And don’t ask me why this is so inconsistent and confusing – it just is, and you’ll have to work with that for now.So in your case, you should try:
Furthermore – your stored proc has problem, since you’re concatenating together
datetimeand string into a string, but you’re not converting thedatetimeto string first, and also, you’re forgetting the close quotes in your statement after both dates.So change this line here to this:
With these settings, and once you’ve fixed your stored procedure which contains problems right now, it will work.