Operand type clash: date is incompatible with int While selecting rows - sql

ALTER PROCEDURE [dbo].[Expense_monthly_report] #start_date VARCHAR(100),
#end_date VARCHAR(100)
AS
BEGIN
DECLARE #SQLQuery AS NVARCHAR(max)
DECLARE #PivotColumns AS NVARCHAR(max)
SET nocount ON;
SELECT #PivotColumns = COALESCE(#PivotColumns + ',', '')
+ Quotename( date_of_expp)
FROM (SELECT DISTINCT Month(date_of_exp) AS date_of_expp
FROM [dbo].[tbl_exp_details]
WHERE date_of_exp >= #start_date
AND date_of_exp <= #end_date) AS PivotExample
SET #SQLQuery = N'SELECT p.part_id,' + #PivotColumns
+ ',total_amount FROM (SELECT part_id,month(date_of_exp) as month_of_exp,exp_amount FROM [dbo].[tbl_exp_details]) as tbl PIVOT( sum(exp_amount) FOR month_of_exp IN ('
+ #PivotColumns
+ ')) AS P join (SELECT part_id,sum(exp_amount) as total_amount FROM [dbo].[tbl_exp_details] where date_of_exp>='
+ #start_date + ' and date_of_exp<=' + #end_date
+ ' group by part_id) as la on p.part_id=la.part_id'
EXEC Sp_executesql #SQLQuery
END
I am getting error
date incompatible with int
. Help me to find out the problem.

You have not delimited the date values in the dynamic query.
So
date_of_exp<=' + #end_date
becomes
date_of_exp<= 2017-07-19
which evaluates to this, and int won't implicitly convert to date
date_of_exp <= 1991
The correct way to use Sp_executesql and fix this is:
SET #SQLQuery = N'SELECT p.part_id,' + #PivotColumns
+ ',total_amount FROM (SELECT part_id,month(date_of_exp) as month_of_exp,exp_amount FROM [dbo].[tbl_exp_details]) as tbl PIVOT( sum(exp_amount) FOR month_of_exp IN ('
+ #PivotColumns
+ ')) AS P join (SELECT part_id,sum(exp_amount) as total_amount FROM [dbo].[tbl_exp_details] where date_of_exp>= #start_date and date_of_exp<=#end_date '
+ ' group by part_id) as la on p.part_id=la.part_id'
EXEC Sp_executesql #SQLQuery,
N'#start_date date, #end_date date',
#start_date,
#end_date

Related

Must declare the scalar variable pivot sql query

i am generating attendance report by pivot SQL on the basis of data thought thumb impression but the query shows error
Must declare the scalar variable "#abc".
here is my query
DECLARE #cols NVARCHAR(MAX)
DECLARE #abc NVARCHAR(MAX)
set #abc='00:00'
SELECT
top 1 #cols = COALESCE(#cols + ',[' + CONVERT(varchar, DateIn ,106 )
+ ']','[' + CONVERT(varchar, DateIn ,106) + ']' )
FROM DailyAttendanceMaster where
DateIn between '2019-01-01 00:00:00.000' and '2019-01-01 00:00:00.000'
group by DateIn order by DateIn asc
DECLARE #qry NVARCHAR(4000) SET
#qry = 'SELECT * FROM (SELECT Employee_Master.Employee_Name,
case when convert(char(5), TimeIn, 108)= convert(char(5), #abc, 108) then "A"
else "B"
end "TimeIn" ,
DailyAttendanceMaster.DateIn FROM DailyAttendanceMaster inner
join Employee_Master on Employee_Master.essl_EmpID=DailyAttendanceMaster.EMPID)emp
PIVOT (MAX(TimeIn) FOR DateIn IN (' + #cols + ')) AS stat'
EXEC(#qry)
You need to pass variable:
EXEC sp_executesql #qry, N'#abc NVARCHAR(MAX)', #abc

Conversion failed when converting date and/or time from character string SQL Server 2012

Pivoting a table using a stored procedure in SQL Server 2012, I get the error. I have provided the stored procedure code:
CREATE PROCEDURE [dbo].[sp_Report_SalesJournal]
(#fromDate DATETIME,
#toDate DATETIME,
#locationId INT)
AS
BEGIN
DECLARE #cols AS NVARCHAR(MAX) = '';
DECLARE #query AS NVARCHAR(MAX) = '';
SELECT #cols = #cols + QUOTENAME(AccountName) + ','
FROM
(SELECT DISTCINT AccountName
FROM vw_SalesJournal
) AS tmp
SELECT #cols = SUBSTRING(#cols, 0, LEN(#cols))
SET #query =
'SELECT * from
(
select InvoiceDate, TransactionNumber, CustomerName, Amount, AccountName from vw_SalesJournal Where (InvoiceDate BETWEEN convert(date,' + #fromDate + ',105) AND convert(date,' + #toDate + ',105)) OR LocationId=' + #locationId + '
) src
pivot
(
max(Amount) for AccountName in (' + #cols + ')
) piv'
I have already gone through and also tried some of the answers provided on similar post.
you need to convert your date to string (with format YYYYMMDD) and enclose the date string in single quote before concatenate
BETWEEN ''' + convert(varchar(10), #fromDate, 121) + ''' AND

Comma seperated values to SQL IN STATEMENT

If i have a comma separated list of values:
A1,B2,B3
How do i pass this into a variable and then form it into an SQL IN statement.
DECLARE #DATE AS VARCHAR(50)
SELECT #DATE = CONVERT(VARCHAR(8), Getdate(), 112)
--PRINT #DATE
DECLARE #TIME AS VARCHAR(50)
--PRINT TIME
SELECT #TIME = Replace(CONVERT(VARCHAR(5), Getdate(), 108), ':', '')
DECLARE #ID AS VARCHAR(50)
SELECT #ID = Replace(W0128001, 32322, 32323, 3232323, 2323232, ',', ',')
--PRINT #ID
DECLARE #QUERY NVARCHAR(MAX);
SET #QUERY = 'SELECT * INTO BACKUPTABLE_' + #DATE + #TIME
+ '
FROM TABLE
WHERE ID IN (' + '''' + #ID + ''')'
--EXEC #query
PRINT #QUERY
I have tried to do a replace above but i want it so that an end user can PASTE into the values and my script will take care of the commas and properly form it. It should also strip out the last commas from the end.
My output needs to read:
SELECT * INTO BACKUPTABLE_201606061503
FROM TABLE
WHERE ID IN ('W0128001','32322','32323','3232323','2323232')
For one thing, you don't surround it with single quotes:
SET #QUERY = 'SELECT * INTO BACKUPTABLE_' + #DATE + #TIME + '
FROM TABLE
WHERE ID IN (' + #ID + ')';
There are other ways to pass comma-delimited values to a SQL statement, including using a split() function or XML.
CREATE PROCEDURE [dbo].[CreateBackupTable]
#ID varchar(100) = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE #DATE VARCHAR(50)= CONVERT(VARCHAR(8), Getdate(), 112);
DECLARE #TIME VARCHAR(50) = Replace(CONVERT(VARCHAR(5), Getdate(), 108), ':', '')
declare #xml xml,#SQL NVARCHAR(MAX);
set #xml = N'<root><r>' + replace(#ID,',','</r><r>') + '</r></root>'
SET #SQL = N' SELECT * INTO ' + QUOTENAME('BACKUPTABLE_' + #DATE + #TIME)
+ N' from TableName '
+ N' where ID IN (
select r.value(''.'',''varchar(max)'') as item
from #xml.nodes(''//root/r'') as records(r)
)'
exec sp_executesql #sql
, N'#ID varchar(100), #xml XML'
, #ID
, #Xml
END

How to grab the value of the output parameter in execute sp_executesql?

Please forgive newbie's ignorance!
How do I grab the value of the output parameter in execute sp_executesql?
I can see the output but cannot get to it:
DECLARE #LastActivity nvarchar(100)
DECLARE #LastActivityDate datetime
DECLARE #sql nvarchar(MAX)
DECLARE #RowsToProcess int
DECLARE #CurrentRow int
DECLARE #SelectCol1 nvarchar(100)
DECLARE #SelectCol2 nvarchar(100)
DECLARE #SelectCol3 nvarchar(100)
DECLARE #LastDate TABLE (RowID int not null primary key identity(1,1), col4 nvarchar(MAX), col5 sql_variant)
DECLARE #table1 TABLE (RowID int not null primary key identity(1,1), col1 nvarchar(100),col2 nvarchar(100),col3 nvarchar(100))
INSERT into #table1 (col1,col2,col3)(SELECT t.name AS col1, c.name AS col2, m.Field1 as col3
FROM sys.columns c INNER JOIN
sys.tables t ON c.object_id = t.object_id INNER JOIN
sys.schemas s ON t.schema_id = s.schema_id INNER JOIN
dbo.MERGE_TABLES m ON m.Table_Name=t.name
WHERE c.name LIKE '%[_]DATE%' and m.[Enabled]='Y')
SET #RowsToProcess=##ROWCOUNT
SET #CurrentRow=0
WHILE #CurrentRow<#RowsToProcess
BEGIN
SET #CurrentRow=#CurrentRow+1
SELECT #SelectCol1=col1,#SelectCol2=col2,#SelectCol3=col3 FROM #table1 WHERE RowID=#CurrentRow
SET #sql='SELECT ' + '[dbo].[ConvertToDatetime](MAX(' + #SelectCol2 + '))' + ' FROM ' + #SelectCol1 + ' Where ' + #SelectCol3 + ' = ' + '''0722607QZ'''
Declare #params as nvarchar(MAX)
Set #params = '#date sql_variant output'
Declare #date as sql_variant;
execute sp_executesql
#sql
,#params
,#date output
Select #date
INSERT into #LastDate VALUES (#sql, #date)
end
select col4,col5 from #LastDate
select col4,col5 from #LastDate gives me the SQL script in clo4 but col5 is empty! I need to store the #date as I still need to get the Max(#date)
Thanx a million.
SET #sql='set #date =('SELECT ' + '[dbo].[ConvertToDatetime](MAX(' +
#SelectCol2 + '))' + ' FROM ' + #SelectCol1 + ' Where ' + #SelectCol3
+ ' = ' + '''0722607QZ''' ) '
the above sql gives me error: Incorrect syntax near '.'
SET #sql='set #date =(SELECT [dbo].[ConvertToDatetime](MAX( + #SelectCol2 + ))
FROM #SelectCol1 Where #SelectCol3 ''=0722607QZ'' ) '
The above sql gives the error: Must declare the scalar variable "#SelectCol2"
SET #sql='SELECT ' + #date + '=convert(nvarchar(100), [dbo].[ConvertToDatetime](MAX(' + #SelectCol2 + ')))' + ' FROM ' + #SelectCol1 + ' Where ' + #SelectCol3 + ' = ' + '''0722607QZ'''
the above produces the error : Implicit conversion from data type sql_variant to nvarchar is not
allowed. Use the CONVERT function to run this query.
SET #sql='SELECT ' + #date + '=convert(nvarchar(MAX),(MAX(' + #SelectCol2 + '))' + ' FROM ' + #SelectCol1 + ' Where ' + #SelectCol3 + ' = ' + '''0722607QZ'''
the above produces no error but all output is NULL, no values.
Your syntax looks ok but you never assign to the output variable #date hence no value.
Instead of;
SET #sql='SELECT ...'
You need;
SET #sql='set #date = (SELECT ...'
Can't you use a better type than sql_variant?

How do I name a column as a date value

the results look like this but wher the column name says 'Today' I want it to be todays date.
Try this technique:
declare #dt datetime
declare #sql varchar(100)
set #dt = getdate()
set #sql = 'select 1 as [ ' + convert( varchar(25),#dt,120) + ']'
exec (#sql)
In your Case:
declare #dt datetime
declare #sql varchar(100)
set #dt = getdate()
set #sql = 'select 0 as [ ' + convert( varchar(25),#dt,120) + ']'
exec (#sql)
I would return an integer representing a day offset and parse it in the client, failing that you are going to have to use dynamic SQL or do something with the underlying column name itself;;
declare #sql nvarchar(128) = '
select
col1,
col2,
0 as [' + cast(getdate() as nvarchar(32)) + ']
from T'
exec(#sql)
Or
--today
declare #now varchar(32) = cast(getdate() as varchar(32))
--result to temp table
select col1, col2, 0 as [Now] into #T from TheTable
--rename col
exec tempdb..sp_rename '#T.Now', #now, 'COLUMN'
--select
select * from #T