get the column value in sql server in subquery - sql

The following is my query and I need to column value in select subquery instead i get column name
#Temp = temporary table
insert into #Temp([dateTime],Reading)
values (#startDate,(select top(1) #trendId from TABLENAME where deviceTimestamp >= #startDate and deviceTimestamp < #tempdt order by deviceTimestamp desc))
ALTER PROCEDURE ProcName
#trendId as nvarchar(max),
#startDate as datetime,
#endDate as datetime
AS
BEGIN
declare #stt varchar(200) = 'select deviceTimestamp,' + #trendId + ' '+'as reading
from TableName
where deviceTimestamp >= '+#startDate+'and deviceTimestamp < '+#endDate+'
order by deviceTimestamp desc'
exec(#stt)END
I get the error :
Conversion failed when converting date and/or time from character string.)

DECLARE #sqlCommand varchar(1000)
DECLARE #columnList varchar(75)
DECLARE #city varchar(75)
SET #columnList = 'AddressID, AddressLine1, City'
SET #city = '''London'''
SET #sqlCommand = 'SELECT ' + #columnList + ' FROM Person.Address WHERE City = ' + #city
EXEC (#sqlCommand)
Check this link out. Dynamic SQL seems like what you need you can pass tablename,table columns dynamicly to your Query. so with this you will be able to pass column name as parameter-variable. otherwise you just selecting plainText as record.

Related

Conversion failed when converting date from character string in a stored procedure

I am facing an issue with running a stored procedure with a Date parameter. I have 2 parameters in a stored procedure which returns a result set from a table. In the table name is of type nvarchar and dateclient is a date.
The value of the parameters are coming from an user interface.
ALTER PROCEDURE [dbo].[NAME_SEARCH]
#name nvarchar(255),
#dateclient datetime
AS
BEGIN
DECLARE #parsed_string nvarchar(max)
EXEC parsing_coi_input #name, #parsed_string OUTPUT
PRINT #parsed_string
SET #name = #parsed_string
DECLARE
#BaseQuery nvarchar(max) = 'SELECT Id, name, date_client
FROM Client
INNER JOIN CONTAINSTABLE (Client, ame,'''+ #name + ''') as name_key ON ID = name_key.[KEY]'
DECLARE
#OrderByQuery nvarchar(max) = ' ORDER BY name_key.RANK'
DECLARE
#OrderDesc nvarchar(max) =' DESC'
BEGIN
SET NOCOUNT ON;
SET #BaseQuery = #BaseQuery + '
INNER JOIN CONTAINSTABLE(Client, date_client,'''+ #dateclient +''') AS
date_clientkey ON ID = date_clientkey.[KEY] WHERE date_client_matter_open >= '+ #dateclientmatter
+''
SET #OrderByQuery = #OrderByQuery + ',date_client_key.RANK'
END
DECLARE #fullQuery nvarchar(max)= #BaseQuery + #OrderByQuery + #OrderDesc
EXECUTE sp_executesql #fullQuery
END
I am executing:
EXEC [dbo].[NAME_SEARCH] 'MGeolo','2009-04-05'
But I get this error:
Conversion failed when converting date and/or time from character string.
Any suggestions how to handle this?
You are missing the ' characters around your date when the SQL script is generated and a cast from datetime to varchar.
You should do like:
BEGIN
SET NOCOUNT ON;
SET #BaseQuery = #BaseQuery + '
INNER JOIN CONTAINSTABLE(Client, date_client,'''+ cast(#dateclient as varchar(200)) +''') AS
date_clientkey ON ID = date_clientkey.[KEY] WHERE date_client_matter_open >= '''+ cast(#dateclientmatter as varchar(200)) +''''
SET #OrderByQuery = #OrderByQuery + ',date_client_key.RANK'
It is probably a typo but the #dateclientmatter is undeclared because in the header you have only #dateclient.

sql Append for value with single quotes - String Concatenation

This extended version on my previous question sql Append for value with single quotes which am trying to fix
DECLARE #fNAME varchar(40) = 'O'brain'
DECLARE #query nvarchar(256)
DECLARE #id nvarchar(5) = '8'
SET #query = 'UPDATE TableName SET columnname = ''' + #fNAME + '''' +'Added on '+ GETDATE() + ''' WHERE Id= ' + convert(nvarchar, #id)
am trying to get below output using
EXEC sp_executesql
Update table name set columnname = 'O''brain Added on Aug 8 2017 11:15AM' where id = 8
Basically am trying to append some text and current date along with name to be updates as text in one column
I would define and execute the query as:
DECLARE #fNAME varchar(40) = 'O''brain';
DECLARE #query nvarchar(256);
DECLARE #id nvarchar(5) = '8';
SET #query = '
UPDATE TableName
SET columnname = #fNAME + '' added on '' + convert(varchar(255), GETDATE() )
WHERE Id = #id';
EXEC sp_executesql #query, N'#fname varchar(40), #id nvarchar(5)', #fname=#fname, #id=#id;
Note: This is not going to format the date exactly as in your question. You haven't chosen a formatting for the date in your code, so I didn't either.
Here is how you would do this with a normal update. There appears to be no reason at all to use dynamic sql here.
DECLARE #fNAME varchar(40) = 'O''brain';
DECLARE #id nvarchar(5) = '8';
Update TableName
set columnname = #fNAME + ' added on ' + convert(varchar(255), getdate())

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.

Passing two values to a stored procedure?

I've written a stored procedure which is called on a link which provides a date value every time and #cg is NULL that time to filter the result on a particular date.
DECLARE #return_value int
EXEC #return_value = [dbo].[Get_Mydata]
#cg = NULL,
#tosearch = '15-05-2014'
SELECT 'Return Value' = #return_value
GO
And after first execution of the stored procedure, it gives some results and using same stored procedure.
I need to filter result by passing below parameter so this time #cg is NOT NULL.
DECLARE #return_value int
EXEC #return_value = [dbo].[Get_Mydata]
#cg = 'CUSTOMER NAME',
#tosearch = 'manish'
SELECT 'Return Value' = #return_value
GO
I'm not able to figure how should I create a dynamic where clause and add it to existing query as well as how to pass value to same parameter which already been passed as date.
More like first getting results for a particular date and then applying like filter on that result. I cannot pass different parameter that's Front end developers requirement.
This is my stored procedure and table data here. http://sqlfiddle.com/#!3/bb917
create proc Get_Mydata
(
#cg varchar(50),
#tosearch varchar(50)
)
as
begin
set nocount on
declare #sqlquery nvarchar(max)
set #sqlquery = N'select q_no, trandate, cust_name from testsp where CONVERT(Date, trandate, 103) = CONVERT(Date, ''' + #tosearch + ''' ,103)';
create table #temp1
(
q_no int,
trandate datetime,
cust_name varchar(50)
)
insert into #temp1(q_no, trandate, cust_name)
exec (#sqlquery)
select * from #temp1 as T;
set nocount off
end
What I have understood is that you want stored procedure to filter results on Date column when you pass null to #cg param and you want to filter results on Cust_name when you pass string 'Cust_Name' to your #Cg Param.
It should be fairly simple, But in any case you do not need a temp table to get the results back its just an over kill of a fairly simple query.
I would do something like this....
Pass the column name to #ColumnName Parameter, and your value to #tosearch parameter. It will build the query depending on what values you pass.
Make sure when you pass a value(Column Name) to #ColumnName.
create proc Get_Mydata
(
#ColumnName varchar(50),
#tosearch varchar(50)
)
as
begin
set nocount on;
declare #sqlquery nvarchar(max);
set #sqlquery = N' select q_no, trandate, cust_name '
+ N' from testsp '
+ N' where ' + QUOTENAME(#ColumnName) + N' = '
+ CASE
WHEN #ColumnName = 'trandate'
THEN N' CAST(#tosearch AS DATE)'
WHEN #ColumnName = 'cust_name'
THEN N' #tosearch'
ELSE N'' END
EXECUTE sp_executesql #sqlquery
,N'#tosearch varchar(50)'
,#tosearch
set nocount off;
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)