- Remove From My Forums
-
Question
-
I have a SQL Server 2000 database that records overtime worked. The table looks like this,
CREATE TABLE [OvertimeTracking] ( [ID] [int] IDENTITY (1, 1) NOT NULL , [EmpID] [varchar] (8) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [OTDate] [smalldatetime] NULL , [OTStartDate] [datetime] NULL , [OTEndDate] [datetime] NULL , [OTLocation] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [OTHoursAdmin] [decimal](8, 2) NULL , [OTHours] [decimal](8, 2) NULL , [Comments] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [Mandatory] [bit] NULL , [Voluntary] [bit] NULL , [FibData] [bit] NULL , [Active] [bit] NULL CONSTRAINT [DF_OvertimeTracking_Active] DEFAULT (1), [InsertedDate] [datetime] NULL , [InsertedBy] [varchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [UpdatedDate] [datetime] NULL , [UpdatedBy] [varchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , CONSTRAINT [PK_OvertimeTracking] PRIMARY KEY CLUSTERED ( [ID] ) ON [PRIMARY] ) ON [PRIMARY] GO
We use this database to track overtime worked and find who has worked overtime recently and who has not.
Management has asked me to modify the database to track refusals to work overtime. I built a table,
CREATE TABLE [Refusals] ( [UID] [int] IDENTITY (1, 1) NOT NULL , [EmpID] [varchar] (8) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [RefusalDate] [smalldatetime] NULL , [RLU] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [Shift] [int] NULL , CONSTRAINT [PK_Refusals] PRIMARY KEY CLUSTERED ( [UID] ) ON [PRIMARY] ) ON [PRIMARY] GO
Now I need to write a query that shows the number of refusals since the last date that the employee worked overtime. I have the query built, but
it is returning a «Internal SQL Server error on query.»SELECT E.EmpID, E.EmpLName + ', ' + EmpFName AS EmpName, ISNULL(SUM(CASE WHEN Active = 1 THEN OT.OTHours ELSE NULL END),0) As TotalOT, ISNULL(AVG(CASE WHEN Active = 1 THEN OT.OTHours ELSE NULL END),0) AS AverageOT, ISNULL(Max(OTDate),'1/1/1900') AS LastDate, P.PosDeptID, EmpSWVTCBegDate, (SELECT COUNT(EmpID) FROM Refusals WHERE EmpID = E.EmpID AND RefusalDate > ISNULL(Max(OTDate),'1/1/1900')) AS RefusalCount FROM OvertimeTracking OT RIGHT JOIN EmpCore.dbo.vuActiveEmployees E ON OT.EmpID = E.EmpID INNER JOIN EmpCore.dbo.tblPosition P ON E.PosID = P.PosID INNER JOIN EmpPersonal.dbo.tblEmpPersonalInfo EP ON E.EmpID = EP.EmpID GROUP BY E.EmpID, E.EmpLName, E.EmpFName, P.PosDeptID, EmpSWVTCBegDate
Any ideas on what I can do to get around this issue?
[Edited to make more readable]
Thanks,
Drew-
Edited by
Tuesday, May 22, 2012 1:19 PM
-
Edited by
Answers
-
Try changing it to this:
GROUP BY r2.EmpID HAVING r2.RefusalDate > Max(coalesce(ot2.OTDate, '1/1/1900'))) r ON OT.EmpID = r.EmpID
Chuck
-
Edited by
Chuck Pedretti
Tuesday, May 22, 2012 5:38 PM -
Marked as answer by
Iric Wen
Wednesday, May 30, 2012 2:05 PM
-
Edited by
-
Just from my head I’ve modifed the script to include a derived table. This may help you:
SELECT Emp.EmpID, Emp.EmpName, Emp.TotalOT, Emp.AverageOT, Emp.LastDate, Emp.PosDeptID, Emp.EmpSWVTCBegDate, COUNT(r.EmpID) AS RefusalCount ( SELECT E.EmpID, E.EmpLName + ', ' + EmpFName AS EmpName, ISNULL(SUM(CASE WHEN Active = 1 THEN OT.OTHours ELSE NULL END),0) As TotalOT, ISNULL(AVG(CASE WHEN Active = 1 THEN OT.OTHours ELSE NULL END),0) AS AverageOT, ISNULL(Max(OTDate),'1/1/1900') AS LastDate, P.PosDeptID, EmpSWVTCBegDate FROM OvertimeTracking OT RIGHT JOIN EmpCore.dbo.vuActiveEmployees E ON OT.EmpID = E.EmpID INNER JOIN EmpCore.dbo.tblPosition P ON E.PosID = P.PosID INNER JOIN EmpPersonal.dbo.tblEmpPersonalInfo EP ON E.EmpID = EP.EmpID GROUP BY E.EmpID, E.EmpLName, E.EmpFName, P.PosDeptID, EmpSWVTCBegDate ) AS Emp LEFT OUTER JOIN Refusals r ON r.EmpID = Emp.EmpID WHERE r.RefusalDate > LastDate GROUP BY Emp.EmpID, Emp.EmpName, Emp.TotalOT, Emp.AverageOT, Emp.LastDate, Emp.PosDeptID, Emp.EmpSWVTCBegDate
Krishnakumar S
-
Marked as answer by
Iric Wen
Wednesday, May 30, 2012 2:05 PM
-
Marked as answer by
I am attempting to retrieve some data from my database, I appear to be able to connect to the database as I do not get an error message after the connection is tested. But when I attempt to run a select query, it causes an internal error.
If I take the FROM part away from the query, the page loads with no data. If I add the FROM part back in, with the table to be selected from, the internal error occurs.
The code is below:
$con = mysqli_connect("50.62.209.87:3306","myusername","mypassword",
"FiveExtras");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT `EventVenue`,`EventDate`,`EventTime`,
`EventPostCode` FROM `event`";
$result = mysqli_query($con, $query);
$row = $result;
echo $row;
halfer
19.7k17 gold badges95 silver badges183 bronze badges
asked Feb 6, 2015 at 18:17
4
Rewrite your connection:
$db_conn = mysqli_connect("$host", "$dbuser", "$dbpass") or die("Unable to connect to the database");
mysql_select_db("$dbase", $db_conn) or die("Unable to select the database");
$query = mysqli_query("SELECT `EventVenue`,`EventDate`,`EventTime`,
`EventPostCode` FROM `event`");
And why $result = $row
?
EDIT: For a better query , use "SELECT * ... "
Makyen♦
31.2k12 gold badges83 silver badges120 bronze badges
answered Feb 6, 2015 at 18:48
GasKaGasKa
546 bronze badges
4
did you change your htacess? Changes to .htacess often cause internal server error. or your host ip is bad(try no-ip.com, they give free subdomains for your ip’s)
i checked it with removed port it worked(well…not connecting but no error about host), so maybe it’s something to do with port
if error 500 remains try get support ticket or email webmaster or get another hosting provider
why would you say no error?
here we go:
Warning: mysqli_query() expects parameter 1 to be mysqli, boolean given
in /home/u451361813/public_html/test.php on line 13
and
Warning: mysqli_connect(): (28000/1045): Access denied for user
'myusername'@'185.28.20.221' (using password: YES) in /home/u451361813
/public_html/test.php on line 3
Failed to connect to MySQL: Access denied for user
'myusername'@'185.28.20.221' (using password: YES)
1st one is for no information returned second for no password
12
В качестве последней задачи при работе с серверами ms sql 2000 пришлось менять структуры логов + нормализовать ранее ненормализованные данные, выделять отдельные словари, сложность была в том, что таблицы логов были огромны, данные, подлежащие нормализации и конвертации, как-то особенно ей не подвергались, ну и плюс наличие всякого рода мусора…ну да ладно, это вступление, суть не в этом, а в том, что после этой нормализации на нескольких серверах стала появляться ошибка:
Internal SQL Server error
причем на вставке только в одну и туже таблицу….лечили сначала перестройкой индексов, потом стали искать hotfix, нашли…
Cumulative list of the hotfixes that are available for SQL Server 2000 SP4
Hotfix information
A supported hotfix is now available from Microsoft, but it is only intended to correct the problem that is described in this article. Only apply it to systems that are experiencing this specific problem. This hotfix may receive additional testing. Therefore, if you are not severely affected by this problem, we recommend that you wait for the next SQL Server 2000 service pack that contains this hotfix.
To resolve this problem immediately, contact Microsoft Product Support Services to obtain the hotfix. For a complete list of Microsoft Product Support Services telephone numbers and information about support costs, visit the following Microsoft Web site:
Из описания проблемы обратил внимание на следующее:
SYMPTOMS
When you run a query or a stored procedure in SQL Server 2000, you may receive an error message that resembles the following:
Server: Msg 8624, Level 16, State 1, Line 1 Internal SQL Server error
This problem occurs when you use a complex insert query that joins several tables. Typically, this problem occurs when the query runs parallel across multiple processors.
When this problem occurs, you may also experience the following symptoms:
• | The query does not run. |
• | You cannot see the SHOWPLAN_ALL or SHOWPLAN_TEXT output for the query. |
Note State 1 and Line 1 in the error message help distinguish this problem from other types of 8624 error messages. If a different state and line number exist in the error message, you are probably not experiencing this problem.
Решил проверить…выдрал тот запрос, на котором собственно и происходила указанная ошибка, решил посмотреть план….
запрос типаinsert into
select
на сам select план получил, решил посмотреть план с учетом insert statement, и…реально увидел сообщение об ошибке….из описания симптомов обратил внимание также на следующее:
This problem occurs when you use a complex insert query that joins several tables. Typically, this problem occurs when the query runs parallel across multiple processors.
Это как раз наш случай, вышеуказанный запрос выполнялся на многопроцессорной машине, при работе c sql server были задействованы все имеющиеся 4ре процессора:
в качестве пробы решил отключить использование параллелизма для рассматриваемого запроса (тем более есть уже такая практика, что при включенном параллелизме запрос выполняется реально медленнее, чем без него, а для моего случая тут он вообще был лишний), используя следующий хинт:
option (maxdop 1), т.е. просто указав, что для моей вставки будет использоваться ресурсы только одного процессора…
т.е.
insert into
select <….>
option (maxdop 1)
посмотрим план, и…ошибка исчезла…
ps: вообщем, для моего случая это стало решением…не знаю, может кому и пригодится, благодарности принимаются в виде пива:)
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|