Incorrect syntax near '2' at line 11. line 11 is "#processdate" variable [closed] - sql-server-2008

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm getting syntax error in #processdate variable, AS per my understanding it is because of date format (sub query that is stored in #processdate variable). I need help AS I am new to sql.
I'm trying to SET all of the query in stored procedure. What I have tried - dIFferent date formats, converting #processdate variable.
ALTER PROCEDURE [dbo].[rec_search_pay]
#processdatefrom DATETIME,
#processdateto DATETIME,
#collectiondatefrom DATETIME,
#collectiondateto DATETIME,
#amount MONEY,
#stationid VARCHAR(10),
#bankcode VARCHAR(2),
#branchcode VARCHAR(6),
#ponumber VARCHAR(10)
AS
BEGIN
DECLARE #bank AS VARCHAR(MAX);
DECLARE #branch AS VARCHAR(MAX);
DECLARE #station AS VARCHAR(MAX);
DECLARE #amounts AS VARCHAR(MAX);
DECLARE #pono AS VARCHAR(MAX);
DECLARE #processdate AS NVARCHAR(MAX);
DECLARE #collectiondate AS NVARCHAR(MAX);
DECLARE #stmt AS VARCHAR(MAX);
DECLARE #linebreak AS VARCHAR(2);
SET #linebreak = CHAR(13) + CHAR(10);
SET #processdate = ' AND h.processdate >= ' + CAST(#processdatefrom AS NVARCHAR) +
' AND h.processdate <= ' + CAST(#processdateto AS NVARCHAR)
SET #collectiondate = ' AND h.collectiondate >= ' + CAST(#collectiondatefrom AS NVARCHAR) +
' AND h.collectiondate <= ' + CAST(#collectiondateto AS NVARCHAR)
IF (#amount LIKE '%[^0-9]')
SET #amounts = ' AND amount = ' + #amount
ELSE
SET #amounts = ' '
IF (#bankcode <> '00')
SET #bank = ' and h.bankcode = ' + #bankcode
ELSE
SET #bank = ' '
IF (#branchcode <> '0')
SET #branch = ' and h.branchcode = ' + #branchcode
ELSE
SET #branch = ' '
IF (#stationid <> 7)
SET #station = ' and h.stationid = ' + #stationid
ELSE
SET #station = ' '
IF (#ponumber LIKE '%[^0-9]')
SET #pono = ' and h.advicenumber = ' + #ponumber
ELSE
SET #pono = ' '
SET NOCOUNT ON;
SET #stmt = 'SELECT h.bankcode, RTRIM(bankname) AS bankname, h.branchcode,
RTRIM(branchname) AS branchname, h.processdate,
h.collectiondate, h.advicenumber, h.amount, h.commission,
h.servicecharges, h.others, h.adjustment, s.stationname, h.userid
FROM banks b, branches br, reconcile h, stations s
WHERE CAST(h.bankcode AS VARCHAR) = b.bankcode
AND CAST(h.bankcode AS VARCHAR) = br.bankcode
AND CAST(h.branchcode AS VARCHAR) = br.branchcode
AND h.stationid = s.stationid
AND returned <> ''Y''
'+ #processdate + #linebreak + --problems seems to be here
+ #collectiondate + #linebreak +
+ #bank + #linebreak +
+ #branch + #linebreak +
+ #station + #linebreak +
+ #amounts + #linebreak +
+ #pono + #linebreak +
'ORDER BY 1, 3, collectiondate'
EXEC (#stmt)
Executing the stored procedure:
exec rec_search_pay '2018-mar-02', '2018-may-01', '2018-mar-01',
'2018-apr-30', 27698, 1, 3, 2003, 4721621
Expected result:
3 /NATIONAL BANK OF PAKISTAN /2003 /C.O.D. DRIGH ROAD [2003]
/2018-04-05 00:00:00.000 /2018-04-02 00:00:00.000 /4721621 /27698.00
/272.00 /0.00 /0.00 /0.00 /Karachi /john
Actual result:
Incorrect syntax near '2'.
Stored procedure(query) using print:
select h.bankcode, rtrim(bankname) AS bankname, h.branchcode,
rtrim(branchname) AS branchname, h.processdate, h.collectiondate,
h.advicenumber, h.amount, h.commission, h.servicecharges, h.others,
h.adjustment, s.stationname, h.userid
from banks b, branches br, reconcile h, stations s
Where cast (h.bankcode AS VARCHAR) = b.bankcode
and cast (h.bankcode AS VARCHAR) = br.bankcode
and cast (h.branchcode AS VARCHAR) = br.branchcode
and h.stationid = s.stationid
and returned <> 'Y'
and h.processdate >= Mar 2 2018 12:00AM and h.processdate <= --prob
May 1 2018 12:00AM
and h.collectiondate >= Mar 1 2018 12:00AM and h.collectiondate <=
Apr 30 2018 12:00AM
and h.bankcode = 3
and h.branchcode = 2003
and h.stationid = 1
order by 1, 3, collectiondate

When you specify date literals in your query, the date value must be surrounded with single quotes. For example this part of your code:
and h.processdate >= Mar 2 2018 12:00AM
If you add quotes, it should become:
and h.processdate >= 'Mar 2 2018 12:00AM'
But it isn't a good idea to use date formats like this. You better use '20180302' for March 2nd, 2018. This will save you a lots of trouble.

Related

"object reference not set to the instance of an object" when i run the query- mssql

Please access the following link.
enter image description here
I would like to calculate the values for each column ( Jul2015 , Aug2015. ) The formula is listed as follows .
MMMYYYY = bookrate * number of days for each activity
e.g row 1 : July2015 = 18937 *23 (from 1/7 - 23/7) ,
row 2: July2015 =20503*9 (from 23/7-31/7) , Aug2015 =20503*20 (1/8-20/8)
*I wrote the following code to try to cater the first row.But it turned out an error message "Object reference not set to an instance of an object" ? May anyone tell me why this message will appear
select * into #tempcost1 from tempcost
Declare #i int
Set #i =1
Declare #numofrow int
Set #numofrow = (Select COunt(*) FROM #tempcost1)
Declare #startmonth datetime
Declare #monthdiff int
Declare #update1 varchar(max)
Declare #month1 varchar(20)
Declare #activitysate datetime
While (#i<=#numofrow)
Begin
Set #monthdiff= (Select diff_month FROM #tempcost1 where RowNumber= #i)
Set #activitysate = (Select activity_startdate FROM #tempcost1 where RowNumber= #i)
Set #month1= SUBSTRING (convert(varchar, #activitysate, 100),1,3) +
SUBSTRING (convert(varchar, #activitysate, 100),8,4 )
if (#monthdiff = 1)
Begin
Set #update1 = 'Update #tempcost1 set ' + CAST(#month1 as varchar) + ' =(Select bookrate from #tempcost1 where Rownumber=' + cast(#i as varchar) +') ' + 'where RowNumber=' + cast(#i as varchar)
exec(#update1)
End
Set #i = #i +1
End

Getting dates between specific dates comma-separated

I have the following table:
CREATE TABLE dbo.Test
(
Name NVARCHAR(50)
,StartDate DATE
,EndDate DATE
)
INSERT INTO dbo.Test VALUES('ABC','28-Feb-14','03-Mar-14')
INSERT INTO dbo.Test VALUES('DEF','04-Mar-14','04-Mar-14')
Basically this contain start and end date of leave for a given user. I am expecting an output as shown below.
Expected output:
Name | WorkHour| LeaveHour | Remarks
-------------------------------------
ABC | 27 | 18 | 28-Feb, 03-Mar
DEF | 36 | 9 | 04-Mar
1 day of leave corresponds to 9 hours and a work week refers to Friday to the next Thursday. In this case that would be from 28-Feb to 06-Mar.
WorkHour refers to number of hours user has worked barring the leaves and not including the weekends.
LeaveHour refers to the number of hours user is on leave.
'Remarks' refers to distinct leaves for the user between StartDate and EndDate values that should appear as comma separated.
I am able to get the work hour (including weekends which is not desired), leave hour values but finding it difficult to have remarks and value excluding weekends
SELECT
RN.Name
,ISNULL(45 - ((DATEDIFF(DD, VT.StartDate, VT.EndDate) + 1) * 9 ), 0) AS 'WorkHours'
,ISNULL(((DATEDIFF(DD, VT.StartDate, VT.EndDate) + 1) * 9 ), 0) AS 'LeaveHours'
--distinct leave dates seperated by comma should be displayed as remarks
FROM
Test VT
LEFT JOIN
ResourceNames RN ON VT.UserId = RN.UserId
Can anyone help?
This should not be done in SQL, but here is a function that will do what you want:
create function CSVDates (#startDate datetime, #endDate datetime)
returns nvarchar(4000)
as
begin
declare #csv nvarchar(4000) = ''
declare #maxDays int = DATEDIFF(DD, #startDate, #endDate)
declare #count int = 0
declare #date datetime
while(#count <= #maxDays )
begin
if (DATENAME(dw, #date) = 'Saturday' OR DATENAME(dw, #date) = 'Sunday')
BEGIN
set #count = #count + 1
CONTINUE
END
set #date = DATEADD(d,#count, #startDate)
if (len(#csv) > 0) set #csv = #csv + ','
set #csv = #csv + DATENAME(day,#date) + '-' + DATENAME(month,#date)
set #count = #count + 1
end
return #csv
end
plug it into your select as CSVDates(vt.StartDate, vt.EndDate)
if you have a lot of dates in between, nvarchar(4000) may not be enough...
I figured out what was going wrong as finally I had time to work on this. Basically the block under weekend was not allowing date to get incremented which was resulting in the data not appearing.
Here is the working code for someone looking for similar ask
create function CSVDates (#startDate datetime, #endDate datetime)
returns nvarchar(4000)
as
begin
declare #csv nvarchar(4000) = ''
declare #maxDays int = DATEDIFF(DD, #startDate, #endDate)
declare #count int = 0
--assign start date
declare #date datetime = #startDate
while(#count <= #maxDays )
begin
if (DATENAME(dw, #date) = 'Saturday' OR DATENAME(dw, #date) = 'Sunday')
begin
--do nothing
set #count =#count
end
else
begin
if (len(#csv) > 0)
set #csv = #csv + ','
set #csv = #csv + DATENAME(day,#date) + '-' + SUBSTRING(DATENAME(month,#date),1,3)
end
set #count = #count + 1
set #date = DATEADD(d,#count, #startDate)
end
return #csv
end

Converting MSSQL function to MySQL function

I am trying to convert this user defined function (taken from a MSSQL) and tweak it so that I can run it MYSQL. I have made several attempts but all seem to error on the declare variable.
I am running the following version: 5.6.11-log - MySQL Community Server (GPL)
USE [DataGB]
GO
/****** Object: UserDefinedFunction [dbo].[FullPostCodeFix] Script Date: 11/20/2013 16:10:44 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE FUNCTION [dbo].[FullPostCodeFix] (#Postcode VARCHAR(20))
RETURNS VARCHAR(20)
BEGIN
/*
Puts postcode into correct format if it is currently in any of the below formats
AB12AA
AB 12AA
AB1 2AA
AB 1 2AA
Returns #Postcode
*/
DECL ARE #District Varchar(50)
DECLARE #Remainder Varchar(50)
DECLARE #Sector Varchar(50)
SET #District= CASE
WHEN LEN(#Postcode) - CHARINDEX(' ', REVERSE(#Postcode)) = len(#Postcode) THEN SUBSTRING(#Postcode,1,(len(#Postcode) - 3))
WHEN LEN(#Postcode) - CHARINDEX(' ', REVERSE(#Postcode)) < 3 THEN SUBSTRING(#Postcode,1,(len(#Postcode) - 3))
ELSE SUBSTRING(#Postcode, 0, LEN(#Postcode) - CHARINDEX(' ', REVERSE(#Postcode)) + 1)
END
SET #District = dbo.PostcodeFix(#District)
SET #Remainder= RIGHT(#Postcode,3)
SET #Sector = #District + ' ' + LEFT(#Remainder,1)
SET #Postcode = #District + ' ' + #Remainder
RETURN #Postcode
END
My attempt at creating a MYSQL version is below:
CREATE FUNCTION FullPostCodeFix (Postcode VARCHAR(20))
RETURNS VARCHAR(20)
BEGIN
DECLARE District Varchar(50)
DECLARE Remainder Varchar(50)
DECLARE Sector Varchar(50)
SET District= CASE
WHEN LEN(Postcode) - CHARINDEX(' ', REVERSE(Postcode)) = len(Postcode) THEN SUBSTRING(Postcode,1,(len(Postcode) - 3))
WHEN LEN(Postcode) - CHARINDEX(' ', REVERSE(Postcode)) < 3 THEN SUBSTRING(Postcode,1,(len(Postcode) - 3))
ELSE SUBSTRING(Postcode, 0, LEN(Postcode) - CHARINDEX(' ', REVERSE(Postcode)) + 1)
END
SET District = dbo.PostcodeFix(District)
SET Remainder= RIGHT(Postcode,3)
SET Sector = District + ' ' + LEFT(Remainder,1)
SET Postcode = District + ' ' + Remainder
RETURN Postcode
END
The error that I get is as follows:
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE Remainder Varchar(50) DECLARE Sector Varchar(50)
There is another function called from within the function "FullPostCodeFix". This is my attempt:
DELIMITER $$
CREATE FUNCTION PostCodeFix (strDistrict VARCHAR(20))
RETURNS VARCHAR(20)
DETERMINISTIC
BEGIN
DECLARE intASCII INTEGER;
SET strDistrict = LTRIM(strDistrict);
SET strDistrict = RTRIM(strDistrict);
IF LENGTH(strDistrict) > 4 OR LENGTH(strDistrict) = 0 THEN RETURN 'ERROR: ' + strDistrict;
ELSE
BEGIN
SET intASCII = ASCII(LEFT(strDistrict, 1));
IF ( intASCII > 47 AND intASCII < 58 ) THEN RETURN 'ERROR: ' + strDistrict;
ELSE
BEGIN
SET intASCII = ASCII(SUBSTRING(strDistrict, 2, 1));
IF ( intASCII > 47 AND intASCII < 58 ) THEN SET strDistrict = LEFT(strDistrict, 1) + ' ' + RIGHT(strDistrict, LENGTH(strDistrict)-1);
SET intASCII = ASCII(SUBSTRING(strDistrict, 3, 1));
IF ( intASCII < 48 OR intASCII > 57 ) AND (intASCII <> 32) THEN RETURN 'ERROR: ' + strDistrict;
ELSE IF LENGTH(strDistrict) < 4 THEN SET strDistrict = LEFT(strDistrict, 2) + ' ' + RIGHT(strDistrict, LENGTH(strDistrict)-2);
END IF;
END IF;
RETURN strDistrict;
END IF;
Ok lets start, replace MS-SQL functions with MySQL equivalent functions.
MSSQL MySQL
LEN() LENGTH()
SUBTRING() SUBSTR()
CHARINDEX() INSTR()
below is documentation and list of all MySQL String functions
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html
Here is correct MySQL Syntax that I have verified.
CREATE FUNCTION FullPostCodeFix (Postcode VARCHAR(20)) RETURNS VARCHAR(20)
BEGIN
DECLARE district VARCHAR(50);
DECLARE remainder VARCHAR(50);
DECLARE sector VARCHAR(50);
IF LENGTH(Postcode) - INSTR(' ', REVERSE(Postcode)) = LENGTH(Postcode) THEN SET district = SUBSTR(Postcode,1,(LENGTH(Postcode) - 3));
ELSEIF LENGTH(Postcode) - INSTR(' ', REVERSE(Postcode)) < 3 THEN SET district = SUBSTR(Postcode,1,(LENGTH(Postcode) - 3));
ELSE SET district = SUBSTR(Postcode, 0, LENGTH(Postcode) - INSTR(' ', REVERSE(Postcode)) + 1);
END IF;
SET District = dbo.PostcodeFix(District);
SET Remainder= RIGHT(Postcode,3);
SET Sector = CONCAT(District,' ',LEFT(Remainder,1));
SET Postcode = CONCAT(District,' ',Remainder);
RETURN Postcode;
END
Here is your second function
CREATE FUNCTION PostCodeFix (strDistrict VARCHAR(20))
RETURNS VARCHAR(20)
DETERMINISTIC
BEGIN
DECLARE intASCII INTEGER;
SET strDistrict = LTRIM(strDistrict);
SET strDistrict = RTRIM(strDistrict);
IF LENGTH(strDistrict) > 4 OR LENGTH(strDistrict) = 0 THEN RETURN 'ERROR: ' + strDistrict;
ELSE
SET intASCII = ASCII(LEFT(strDistrict, 1));
IF ( intASCII > 47 AND intASCII < 58 ) THEN RETURN 'ERROR: ' + strDistrict;
ELSE
SET intASCII = ASCII(SUBSTRING(strDistrict, 2, 1));
IF ( intASCII > 47 AND intASCII < 58 ) THEN SET strDistrict = LEFT(strDistrict, 1) + ' ' + RIGHT(strDistrict, LENGTH(strDistrict)-1);
END IF;
SET intASCII = ASCII(SUBSTRING(strDistrict, 3, 1));
IF ( intASCII < 48 OR intASCII > 57 ) AND (intASCII <> 32) THEN RETURN 'ERROR: ' + strDistrict;
ELSEIF LENGTH(strDistrict) < 4 THEN SET strDistrict = LEFT(strDistrict, 2) + ' ' + RIGHT(strDistrict, LENGTH(strDistrict)-2);
END IF;
END IF;
RETURN strDistrict;
END IF;
END

Syntax errors in dynamic SQL with database name as variable [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
SQL Server: how to get a database name as a parameter in a stored procedure
In the below stored procedure I am passing the database name as a parameter, but currently for testing I am database name via string which is declare in the procedure.
Please advise as I get an error in SET syntax and it's not able to recognise the db name I am passing.
USE [smtpFetch]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[checkForUpdateV]
(
#ctsCode Varchar(100)
)
As
BEGIN
Declare #dbName varchar(100)
Declare #stDB TABLE
(
change_version_state varchar(max),
change_version_status varchar(200),
uniqueid varchar(20),
Country_code varchar(15),
Research_date varchar(15),
data_date varchar(15),
Make varchar(50),
Model varchar(50),
Versions varchar(255),
Model_year varchar(15),
doors varchar(5),
body varchar(5)
);
DECLARE #number_days as INT
DECLARE #DATAD as nvarchar(max)
DECLARE #DATAD2 as varchar(max)
SET #number_days = 5
SET #ctsCode=#ctsCode
SET #dbName='SSCRUS_CS2002'
SET #DATAD =N'Delete from ' + #ctsCode
select #DATAD
--print #dbName;
set #DATAD2=#DATAD2
INSERT INTO #stdb
set #DATAD2 = "SELECT
STUFF(
( SELECT ', ' + st105.full_text
FROM" + #dbName + ".dbo.version v2
JOIN " + #dbName + ".dbo.equipment e105
ON e105.vehicle_id = v2.vehicle_id AND e105.schema_id = 105
JOIN " + #dbName + ".dbo.schema_text st105
ON st105.schema_id = 105 AND st105.data_value = e105.data_value AND st105.language_id = 19
WHERE (DATEDIFF(day, { fn NOW() }, CONVERT(datetime, CONVERT(char(8), v2.id_103))) > - #number_days) AND
v.vehicle_id = v2.vehicle_id
FOR XML PATH('')
),1,1,''
) AS Change_version_state,
STUFF(
( SELECT ', ' + st106.full_text
FROM " + #dbName + ".dbo.version v3
JOIN " + #dbName + ".dbo.equipment e106
ON e106.vehicle_id = v3.vehicle_id AND e106.schema_id = 106
JOIN " + #dbName + ".dbo.schema_text st106
ON st106.schema_id = 106 AND st106.data_value = e106.data_value AND st106.language_id = 19
WHERE (DATEDIFF(day, { fn NOW() }, CONVERT(datetime, CONVERT(char(8), v3.id_103))) > - #number_days) AND
v.vehicle_id = v3.vehicle_id
FOR XML PATH('')
),1,1,''
) AS Change_version_status,
v.id_101 AS [Unique ID],
v.id_109 AS Country,
v.id_103 AS [Research Date],
v.id_104 AS [Data Date],
v.id_128 AS Make,
v.id_129 AS Model,
v.id_131 AS Version,
v.id_108 AS [Model Year],
v.id_605 AS Doors,
v.id_606 AS Body
FROM " + #dbName + ".dbo.version v
WHERE (DATEDIFF(day, { fn NOW() }, CONVERT(datetime, CONVERT(char(8), v.id_103))) > - #number_days)
ORDER BY [Unique ID], Change_version_status, Change_version_state"
execute sp_executesql #DATAD2
--select * from #stdb
END
Above stored procedure gives an error
Msg 156, Level 15, State 1, Procedure checkForUpdateV, Line 41
Incorrect syntax near the keyword 'set'.
Msg 103, Level 15, State 4, Procedure checkForUpdateV, Line 45
The identifier that starts with '.dbo.equipment e105
ON e105.vehicle_id = v2.vehicle_id AND e105.schema_id = 105
' is too long. Maximum length is 128.
Msg 103, Level 15, State 4, Procedure checkForUpdateV, Line 47
The identifier that starts with '.dbo.schema_text st105
ON st105.schema_id = 105 AND st105.data_value = e105.data_value
AND st105.lang' is too long. Maximum length is 128.
Msg 103, Level 15, State 4, Procedure checkForUpdateV, Line 58
The identifier that starts with '.dbo.equipment e106
ON e106.vehicle_id = v3.vehicle_id AND e106.schema_id = 106
' is too long. Maximum length is 128.
Msg 103, Level 15, State 4, Procedure checkForUpdateV, Line 60
The identifier that starts with '.dbo.schema_text st106
ON st106.schema_id = 106 AND st106.data_value = e106.data_value
AND st106.lang' is too long. Maximum length is 128.
Msg 103, Level 15, State 4, Procedure checkForUpdateV, Line 78
The identifier that starts with '.dbo.version v
WHERE (DATEDIFF(day, { fn NOW() }, CONVERT(datetime,
CONVERT(char(8), v.id_103))) > - #number_days)
ORDER ' is too long. Maximum length is 128.
Your syntax has a few issues.
You can't do a SET operation as part of a an INSERT statement.
INSERT INTO #stdb
set #DATAD2 = "SELECT
Don't use double quotes for dynamic SQL
set #DATAD2 = "SELECT
should be
set #DATAD2 = 'SELECT
Watch your spacing when using the + syntax:
FROM" + #dbName + ".dbo.version v2
should be
FROM ' + #dbName + '.dbo.version v2
Following code is parse "Command(s) completed successfully." on mu ssms. I have remove all the sysntext error from your code. Hope this help
USE [smtpFetch]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[checkForUpdateV]
(
#ctsCode Varchar(100)
)
As
BEGIN
Declare #dbName varchar(100)
Declare #stDB TABLE
(
change_version_state varchar(max),
change_version_status varchar(200),
uniqueid varchar(20),
Country_code varchar(15),
Research_date varchar(15),
data_date varchar(15),
Make varchar(50),
Model varchar(50),
Versions varchar(255),
Model_year varchar(15),
doors varchar(5),
body varchar(5)
);
DECLARE #number_days as INT
DECLARE #DATAD as nvarchar(max)
DECLARE #DATAD2 as varchar(max)
SET #number_days = 5
SET #ctsCode=#ctsCode
SET #dbName='SSCRUS_CS2002'
SET #DATAD =N'Delete from ' + #ctsCode
select #DATAD
--print #dbName;
set #DATAD2=#DATAD2
--INSERT INTO #stdb
Select #DATAD2 = ' INSERT INTO #stdb SELECT
STUFF(
( SELECT '','' st105.full_text
FROM ' + #dbName + '.dbo.version v2
JOIN ' + #dbName + '.dbo.equipment e105
ON e105.vehicle_id = v2.vehicle_id AND e105.schema_id = 105
JOIN ' + #dbName + '.dbo.schema_text st105
ON st105.schema_id = 105 AND st105.data_value = e105.data_value AND st105.language_id = 19
WHERE (DATEDIFF(day, { fn NOW() }, CONVERT(datetime, CONVERT(char(8), v2.id_103))) > - #number_days) AND
v.vehicle_id = v2.vehicle_id
FOR XML PATH('')
),1,1,''
) AS Change_version_state,
STUFF(
( SELECT '', '' + st106.full_text
FROM ' + #dbName + '.dbo.version v3
JOIN ' + #dbName + '.dbo.equipment e106
ON e106.vehicle_id = v3.vehicle_id AND e106.schema_id = 106
JOIN ' + #dbName + '.dbo.schema_text st106
ON st106.schema_id = 106 AND st106.data_value = e106.data_value AND st106.language_id = 19
WHERE (DATEDIFF(day, { fn NOW() }, CONVERT(datetime, CONVERT(char(8), v3.id_103))) > - #number_days) AND
v.vehicle_id = v3.vehicle_id
FOR XML PATH('')
),1,1,''
) AS Change_version_status,
v.id_101 AS [Unique ID],
v.id_109 AS Country,
v.id_103 AS [Research Date],
v.id_104 AS [Data Date],
v.id_128 AS Make,
v.id_129 AS Model,
v.id_131 AS Version,
v.id_108 AS [Model Year],
v.id_605 AS Doors,
v.id_606 AS Body
FROM ' + #dbName + '.dbo.version v
WHERE (DATEDIFF(day, { fn NOW() }, CONVERT(datetime, CONVERT(char(8), v.id_103))) > - #number_days)
ORDER BY [Unique ID], Change_version_status, Change_version_state'
execute sp_executesql #DATAD2
--select * from #stdb
END
-- Temp table
Create table ##stDB (
change_version_state varchar(max),
change_version_status varchar(200),
uniqueid varchar(20),
Country_code varchar(15),
Research_date varchar(15),
data_date varchar(15),
Make varchar(50),
Model varchar(50),
Versions varchar(255),
Model_year varchar(15),
doors varchar(5),
body varchar(5)
)

SQLServer Pivot query

I am working on a appliaction in which I have a following schema
Tasks Master
Task_ID
Task_Name
Task_Details
Task_ID
Task_Date
Task_Count (can be any number like 2 or 3 or 4 or 40)
the Input Form is like that which the staff will fill at the end of the day.
Date | Task Name | Task_Count
24/01/2010 | How many cheque books issued today | 12
24/01/2010 | How many ATM Issued today | 7
Now I want a matrix report showing all tasks suppose 28 tasks in vertical row and on given month it should show all the dates of the particular month horizontal direction like from 1 to 31 days or 30 or 28 as per month days with the task_count using PIVOT in query. i am failed to produce the result as i dont know to make it work. please help.
thanks
You'll need to use a dynamic query since the columns returned by the pivot changes each month.
With some time this could probably be made more elegant, but here's the basic idea:
declare #StartOfMonth datetime = '11/1/2010';
declare #counter datetime = #StartOfMonth;
declare #sql varchar(MAX) = '';
declare #columnnames varchar(MAX);
declare #columnfilter varchar(MAX);
declare #fieldname varchar(12);
--First, create a string of dynamic columns, one for each day of the month.
WHILE (MONTH(#counter) = MONTH(#StartOfMonth))
BEGIN
SET #fieldname = '[' + CONVERT(varchar(10), #counter, 101) + ']';
--Wrap the columns in ISNULL(#,0) to avoid having null values for days without tasks.
SET #columnnames = ISNULL(#columnnames + ',', '') + 'ISNULL(' + #fieldname + ',0) AS ' + #fieldname;
--Also create a dynamic list of the Task_Date values to include in the pivot.
SET #columnfilter = ISNULL(#columnfilter + ',', '') + #fieldname;
SET #counter = DATEADD(DAY,1,#counter);
END
--Put it all together into a pivot query.
set #sql = 'SELECT Task_Name, ' + #columnnames + ' FROM (';
set #sql = #sql + 'SELECT M.Task_Name, D.Task_Date, D.Task_Count '
set #sql = #sql + 'FROM Task_Detail D JOIN Task_Master M ON D.Task_ID = M.Task_ID) as SourceTable ';
set #sql = #sql + 'PIVOT (SUM(Task_Count) FOR Task_Date IN (' + #columnfilter + ')) AS PivotTable';
exec (#sql)