T-SQL Conversion failed when converting datetime from character string - sql

I am using the following stored procedure which takes a datetime variable as input
ALTER PROCEDURE dbo.report #createfrom as datetime=null,#createto as datetime=null
AS
BEGIN
declare #sql varchar(1000)
declare #s datetime;
declare #s1 datetime;
--set #createfrom='7/7/2014 12:00:00 AM'(my input is like in this format)
set #sql = N'select * from table1 where createdon >=''' + cast(#createfrom as datetime) + '''and createdon <=''' + cast(#createto as datetime) + ''' AND createdon is not null'
exec(#sql)
END
I don't know what I am doing wrong. createdon is a datetime variable in the table1. I have given the input parameter format within the code itself. I want to stick to cast instead of convert

I know you said you wanted to stick to cast over convert, but it might be best to format the date as yyyymmdd in your string
e.g.
ALTER PROCEDURE dbo.report #createfrom as datetime=null,#createto as datetime=null
AS
BEGIN
declare #sql varchar(1000)
declare #s datetime;
declare #s1 datetime;
--set #createfrom='7/7/2014 12:00:00 AM'(my input is like in this format)
set #sql = N'select * from table1 where createdon >=''' + CONVERT(VARCHAR(8), #createfrom, 112) + '''and createdon <=''' + CONVERT(VARCHAR(8), #createto, 112) + ''' AND createdon is not null'
exec(#sql)
END

Related

Create a new table every time though a stored procedure

I want create a new table every time though a stored procedure.
declare #datetime datetime
declare #date varchar(20)
select #datetime = (GETDATE() - 1)
select #date = convert(varchar(10), #datetime, 112)
print #datetime
print #date
create table #businessmster+'_'+#date
(
contentid int
)
Table name which I want is #businessmaster_20171103
You can use this query.
Declare #strTableName varchar(500)
SET #strTableName = 'create table businessmster_' + #date +'( contentid int )
GO
INSERT INTO businessmster_' + #date +' Select Field FROM <<YourTable>> WHERE <<Condition>>
GO'
Print #strTableName
Exec(#strTableName)
You can use dynamic query as:
DECLARE #TableName NVARCHAR(MAX);
SET #TableName = N'CREATE TABLE businessmaster_'+
CONVERT(VARCHAR(10),GetDate()-1,112)+
N' ( contentid int )';
SELECT #TableName
EXEC(#TableName);
According to your comment I remove the # symbol.

Assigning values returned by function in Dynamic SQL

I am trying to generate a dynamic SQL to assign variables with values from a function. I am trying to generate SQL something like
Select #StartDate=#EID_Dept
from dbo.WorkHistory(#today,#EID )
The function returns a date (#EID_dept will be the name of the column returned by the function) which I need to assign to #StartDate. And #EID_Dept is generated by concatenating #EID and #dept.
If I manually write the SQL it would appear as
Select #StartDate = amaan_IT
from dbo.WorkHistory('2016-10-10', amaan)
My code is below:
DECLARE #EID varchar(5), #StartDate VARCHAR(MAX),
#today DATETIME, #dept VARCHAR(10), #EID_dept varchar(20);
Select #today = SYSDATETIME()
Select #dept = dept from dbo.Dept(#EID)
Select #EID_Dept = CONCAT(#EID, #dept)
DECLARE #SQL Varchar(max);
SET #SQL = N'Select #StartDate = #EID_Dept
from dbo.PeriodHistory(#today, #EID)';
EXEC Sp_executesql
#SQL,
N'#StartDate VARCHAR(MAX) out,#EID_dept varchar(max),#today datetime,#EID Varchar',
#StartDate out,
#EID_Dept=#EID_Dept,
#today=#today
I changed your query a little bit. Hope this will work fine:
DECLARE #EID nvarchar(5),
#StartDate nvarchar(MAX),
#today datetime = SYSDATETIME(),
#dept nvarchar(10),
#EID_dept nvarchar(20),
#SQL nvarchar(max),
#params nvarchar(max) = N'#StartDate nvarchar(MAX) out, #today datetime, #EID nvarchar(5)'
Select #dept = dept from dbo.Dept(#EID)
Select #EID_Dept = CONCAT(#EID, #dept)
SET #SQL = N'Select #StartDate = ' + QUOTENAME(#EID_dept) + ' from dbo.PeriodHistory(#today, #EID);';
EXEC sp_executesql #SQL,
#params,
#StartDate = #StartDate out,
#today = #today,
#EID = #EID
SELECT #StartDate
I used nvarchar(max) for #SQL (you are using varchar but adding N when assign value to variable). sp_executesql awaits nvarchar in statement part
Is a Unicode string that contains a Transact-SQL statement or batch.
All parameters I put in #params variable.
As I understood you need to get another columns based on #EID_dept, so I add QUOTENAME and used this variable in SQL statement building directly. You can not send column name as variable.

Concatenate Date in sql Dynamic query

I am trying to execute a dynamic query in which I am concatenating a date but failed in doing
DECLARE #pStartDate datetime
DECLARE #pEndDate datetime
DECLARE #query nvarchar(MAX)
Dynamic query1
set #query = 'Select * from Table1 From tblEvent
Where (EventDate Between' + #pStartDate + ' and ' + #pEndDate +')'
Exec(#query)
Error
Conversion failed when converting date and/or time from character string.
Dynamic query2
set #query = 'Select * from Table1 From tblEvent
Where (EventDate Between' + cast(#pStartDate as varchar) + ' and ' + cast(#pEndDate as varchar) +')'
Exec(#query)
Error
Incorrect syntax near 1 [1 stands for whatever date I passed to #pStartDate]
Please suggest me how to do it.
Thanks.
The really proper way to do this would be to use a parametrized query and having sp_executeSql execute this:
DECLARE #pStartDate datetime
DECLARE #pEndDate datetime
DECLARE #query nvarchar(MAX)
SET #pStartDate = '20080301'
SET #pEndDate = '20080331'
-- if you're setting a NVARCHAR variable - **DO USE** the N'..' prefix!
SET #query = N'SELECT * FROM dbo.Table1
WHERE OrderDate BETWEEN #StartDate AND #EndDate'
-- execute the dynamic SQL, with a list of parameters, and their values
EXEC sp_executesql #query,
N'#StartDate DATETIME, #EndDate DATETIME',
#StartDate = #pStartDate, #EndDate = #pEndDate
In that case, there's no fiddling around with string concatenation and missing quotes and messy stuff like that - just a clear, properly parametrized query that isn't vulnerable to SQL injection attacks, and that performs much better since it's execution plan can be reused for subsequent executions.
Add single quote.
Because date or string specify in single quote like this '12-01-2014'.
set #query = 'Select * from Table1 From tblEvent
Where (EventDate Between''' + #pStartDate + ''' and ''' + #pEndDate +''')'

Report Builder paramter dropdown to choose column name

I have a parameter with the available values as column names and a I am using that parameter in the sql query
WHERE ((#ColumnName) BETWEEN (#StartDate) AND (#EndDate))
AND (schema.table.column_name LIKE (#Number))
When i try to run the report i get a cannot convert date/time from characters
If i remove the #ColumnName parameter the report runs fine but i want the ability to choose a column to search the date against.
If you want pass Column name dynamically you will need to use a stored procedure to do this using dynamic sql something like this....
CREATE PROCEDURE Get_Data
#ColumnName1 SYSNAME,
#ColumnName2 SYSNAME,
#StartDate DATETIME,
#EndDate DATETIME,
#Number VARCHAR(100)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL NVARCHAR(MAX);
SET #SQL = N'SELECT * FROM TableName'
+ N'WHERE ' + QUOTENAME(#ColumnName1) + N' BETWEEN #StartDate AND #EndDate '
+ N' AND ' + QUOTENAME(#ColumnName2) + N' LIKE ''#Number'' '
EXECUTE sp_executesql #SQL
,N'#StartDate DATETIME, #EndDate DATETIME, #Number VARCHAR(100)'
,#StartDate
,#EndDate
,#Number
END

How to use DATETime Column in dynamic query in sql server?

I have a Stored Proc which is using for Search Applicants is written as below:
/*
AUTHOR :
CREATION DATE :
NOTES :
PURPOSE :
MODIFIED BY :
MODIFICATION DATE :
*/
ALTER PROCEDURE USP_GET_ApplicantByFilter
(
#ApplicantName VARCHAR(100)='Ram',
#AgeFrom INT=0,
#AgeTo INT=0,
#Experience INT=0,
#ExperienceMonths INT=0,
#City VARCHAR(100)='',
#QualificationID INT=0,
#PositionID INT=0,
#ApplyDateFrom DATETIME='2010-06-29 00:00:00.000',
#ApplyDateTo DATETIME=NULL,
#SortColumn Varchar(128)='ApplicantID',
#SortDirection Varchar(56)='desc',
#Page int=1,
#RecsPerPage int =10
)
AS
DECLARE #SQL VARCHAR(MAX)
DECLARE #DSQL VARCHAR(MAX)
DECLARE #whereCondition VARCHAR(1024)
DECLARE #FirstRec int, #LastRec int
SET #FirstRec = (#Page - 1) * #RecsPerPage
SET #LastRec = (#Page * #RecsPerPage + 1)
Declare #SectionCount int;
Set NoCount On
Begin
SET #SQL='Select ROW_NUMBER() over( order by '+#SortColumn + ' ' +#SortDirection +') rownum, tblApplicants.ApplicantID, tblApplicants.ApplicantName, tblApplicants.FatherName, tblApplicants.DateOfBirth, tblApplicants.QualificationID, tblApplicants.EMailID, tblApplicants.Address, tblApplicants.City, tblApplicants.State, tblApplicants.Phone,
tblApplicants.ApplyDate, tblApplicants.PositionID, tblApplicants.isActive, tblPositionMaster.PositionName
FROM tblApplicants INNER JOIN tblPositionMaster ON tblApplicants.PositionID = tblPositionMaster.PositionID
WHERE 1=1 AND tblApplicants.isActive=1 '
if #ApplicantName!=''
begin
SET #sql +=' AND tblApplicants.ApplicantName like ''%'+ #ApplicantName +'%'''
end
if #AgeFrom!=0
begin
SET #SQL+=' AND DATEDIFF(YEAR,tblApplicants.DateOfBirth, GETDATE()) >= '+#AgeFrom
end
if #AgeTo!=0
begin
SET #SQL+=' AND DATEDIFF(YEAR,tblApplicants.DateOfBirth, GETDATE()) <= '+#AgeTo
end
if #ApplyDateFrom IS NOT NULL
begin
SET #SQL+= ' AND CONVERT(DATETIME,tblApplicants.ApplyDate,101) ='+ CONVERT(DATETIME,#ApplyDateFrom,101)
end
SET #DSQL ='SELECT * from (' + #SQL +') AS tbl'
print #DSQL
DECLARE #TEMPResult TABLE(RowNum INT,
ApplicantID int,
ApplicantName varchar(100),
FatherName varchar(200),
DateOfBirth DATETIME,
QualificationID int,
EMailID varchar(200),
Address varchar(200),
City varchar(200),
State varchar(200),
Phone varchar(200),
ApplyDate DATETIME,
PositionID int,
isActive int,
PositionName varchar(200)
)
INSERT INTO #TEMPResult EXEC(#DSQL)
SELECT (Select Count(*) from #TEMPResult) as Count, * FROM #TEMPResult WHERE RowNum > #FirstRec AND RowNum < #LastRec
RETURN
END
i want to apply "=>" and "<=" operators on ApplyDate. every time i got "*Conversion failed when converting date and/or time from character string.
*"
please help me how can apply these operators on ApplDate
SET #SQL+= ' AND CONVERT(DATETIME,tblApplicants.ApplyDate,101) ='+ CONVERT(DATETIME, #ApplyDateFrom, 101)
change it to:
SET #SQL+= ' AND CONVERT(DATETIME, tblApplicants.ApplyDate, 101) = CONVERT(DATETIME, ''' + cast(#ApplyDateFrom as nvarchar) + ''', 101)'
Replace this line
AND CONVERT(DATETIME,tblApplicants.ApplyDate,101) ='+ CONVERT(DATETIME,#ApplyDateFrom,101)
Updated
AND DATEDIFF(DD,tblApplicants.ApplyDate, CAST(''' + CAST(#ApplyDateFrom as varchar) + ''' as datetime)) = 0
for more look this query
DECLARE #ApplyDateFrom DATETIME='2010-06-29 00:00:00.000'
DECLARE #QUERY varchar(max)
SET #QUERY =
'SELECT DATEDIFF(DD,GETDATE(), CAST(''' + CAST(#ApplyDateFrom as varchar) + ''' as datetime))'
PRINT #QUERY
#AgeFrom is an int. You need to convert it to a varchar before concatentating it to a string.
'AND DATEDIFF(YEAR,tblApplicants.DateOfBirth, GETDATE()) >= '+convert(varchar(5),#AgeFrom)
Not that this will work, of course, as datediff(year... won't give you an age. eg:
select DATEDIFF(YEAR,'2000-12-25','2013-10-01')
will return 13, not 12.
Similarly for ApplyDate convert that to a string
CONVERT(DATE,tblApplicants.ApplyDate,101) = ''' + CONVERT(varchar(20),#ApplyDateFrom,111) + ''''
To be honest though, this whole approach looks like a bad idea to me.
you just need to make sure the parameter before it come into your stored procedured is in this format yyyy-MM-dd HH:mm:ss
then you're save to compare using "<=" and ">=" and doesn't need to convert it to other format just compare like this
tblApplicants.ApplyDate >='2013-10-01 18:00:00'
You need to cast applydate to string before concatenate to dynamics sql.
Mean
SET #SQL+= ' AND CONVERT(DATETIME,tblApplicants.ApplyDate,101) ='+ cast (CONVERT(DATETIME,#ApplyDateFrom,101) AS VARCHAR)