sql server - PHP mssql_query errors when converting date and/or time from character string
I am using PHP to query some data on SQL Server 2008 R2 and receiving the following errors:
- PHP Warning: mssql_query(): message: Conversion failed when converting date and/or time from character string. (severity 16) in /var/www/html/BSC_Entry.php on line 14
- PHP Warning: mssql_query(): General SQL Server error: Check messages from the SQL Server (severity 16) in /var/www/html/BSC_Entry.php on line 14
Here's the code block:
3 <?php // Initialise all database actions
4 //IP of server
5 $server = 'x.x.x.x';
6
7 // Connection to MSSQL - possibly use password file
8 $link = mssql_connect($server, 'user', 'pass');
9 if (!$link) {
10 die('Something went wrong while connecting to MSSQL');
11 }
12
13 // Declare query to return BSC_Name, BSC_Owner and
14 $qBSCInfo = mssql_query('SELECT * FROM dbo.BSC_Info;', $link);
15
16 ?>
Initially, I was passing the SQL below as a parameter to mssql_query, but after receiving the errors, created the database view above 'BSC_Info' (with appropriate permissions) in case the query was too complex for mssql_query to handle:
SELECT DISTINCT
dbo.BSC.BSC_ID,
dbo.BSC.BSC_Name,
dbo.BSC.BSC_Owner,
DATEDIFF(M, MAX(CONVERT(DATETIME, LEFT(dbo.BSCDataSet.DatePeriod, 4)
+ RIGHT(dbo.BSCDataSet.DatePeriod, 2) + '01')), CONVERT(DATETIME, LEFT(CONVERT(VARCHAR, GETDATE(), 120), 4) + RIGHT(LEFT(CONVERT(VARCHAR, GETDATE(),
120), 7), 2) + '01')) AS Periods_to_Current
FROM dbo.BSC
LEFT OUTER JOIN dbo.BSCDataSet
ON dbo.BSC.BSC_ID = dbo.BSCDataSet.BSC_ID
GROUP BY dbo.BSC.BSC_ID, dbo.BSC.BSC_Name, dbo.BSC.BSC_Owner
To clarify, the query works in SQL Server Management Studio returning some fields from a table along with the difference (in months) between the current date and an earlier date (stored in the database as a VARCHAR - YYYYMM format). In order to prevent any issues with partial months, I've set the compared dates to the first day of the month. I am sure there's a more graceful way of doing this, but I have very little SQL Server experience, or PHP for that matter!
Data types are:
- BSC_ID - numeric(5,0)
- BSC_Name - varchar(50)
- BSC_Owner - varchar(50)
- Periods_to_Current - int
Any help would be much appreciated. Cheers all!
Answer
Solution:
So there were a number of issues with this code:
I have now amended the code to a more appropriate (and working):
Hopefully this will help someone out!