How Do I get value from sql search based on the start and end dates? - sql

I have a Personnel Roles Table where employees are assigned daily roles or roles with specific start and end dates.
Managers have asked for a sort of manpower plan table which lists an employee’s daily role and this how I generate the table
private string CreateHTMLTable(Int32 month)
{
StringBuilder strBuilder = new StringBuilder();
System.Data.DataTable dtAllStaff = new System.Data.DataTable();
//get all staff
PersonelApplication.Classes.PersonelClass PersonnelClass = new PersonelClass();
dtAllStaff = PersonnelClass.GetAllPersonel();
//create manpower data table
System.Data.DataTable dtManPowerDataTable = new System.Data.DataTable();
//create montlhy dt
//get number of days in month
int daysInMonth = DateTime.DaysInMonth(DateTime.Now.Year, month);
//get first day in month
DateTime firstDayInMonth = new DateTime(DateTime.Now.Year, month, 1);
//get last day in month
DateTime lastDayInMonth = new DateTime();
lastDayInMonth = firstDayInMonth.AddMonths(1).AddDays(-1);
//start table
strBuilder.Append("<table>");
//create header based on number of days in the month
//append tr strat
strBuilder.Append("<tr>");
//add name header for personnle
strBuilder.Append("<th>");
strBuilder.Append("Staff");
strBuilder.Append("</th>");
for (int i = 1; i <= lastDayInMonth.Day; i++)
{
strBuilder.Append("<th>");
strBuilder.Append(i.ToString() + "/" + month.ToString());
strBuilder.Append("</th>");
}
//append tr end to header row
strBuilder.Append("</tr>");
System.Data.SqlClient.SqlConnection sqlConn = new System.Data.SqlClient.SqlConnection();
sqlConn.ConnectionString = ConnectionClass.CreateConnection.getConnectionString();
using (sqlConn = ConnectionClass.CreateConnection.publicGetConn())
{
sqlConn.ConnectionString = ConnectionClass.CreateConnection.getConnectionString();
try
{
sqlConn.Open();
if (sqlConn.State == ConnectionState.Open)
{
foreach (DataRow row in dtAllStaff.Rows)
{
string personnelName = "";
string personnelCode = "";
Int32 personnelID = 0; ;
personnelCode = row[1].ToString();
strBuilder.Append("<tr>");
strBuilder.Append("<td>");
strBuilder.Append(personnelCode);
strBuilder.Append("</td>");
for (int i = 1; i <= lastDayInMonth.Day; i++)
{
//here get the each employee's planned role as well
//as actual role
}
strBuilder.Append("</tr>");
}
}
}
catch (Exception ex)
{
//pouplate later
}
finally
{
}
}
//end table
strBuilder.Append("</table>");
return strBuilder.ToString();
}
My issue is the SQL function which will return the employees role for a particular day.
--actual end date for this role is '08-18-2012'
declare #sdate date
set #sdate= '08-14-2012'
SELECT
CONVERT(date,startdate,101)
,CONVERT(date,EndDate,101)
,StartDate
,EndDate
,fk_PersonelID
,fk_RoleID
FROM [dbo].JobRolesTable
where #sdate between StartDate and EndDate
and fk_PersonelID = 40
But If I do a search for the next day which is the '08-15-2012’,I get nada
Bascially I want to return an employee’s role on any day of the month and ‘na’ if there’s none
I don’t want to use a cursor for this but is there another way I can achieve this

DECLARE #sdate DATE = '20120814';
SELECT
CONVERT(DATE,StartDate,101) -- what is the purpose of 101 here?
,CONVERT(DATE,EndDate,101) -- what is the purpose of 101 here?
,StartDate
,EndDate
,fk_PersonelID
,fk_RoleID
FROM [dbo].JobRolesTable
WHERE #sdate >= StartDate
AND #sdate < DATEADD(DAY, 1, EndDate)
AND fk_PersonelID = 40;

You are probably populating your parameters incorrectly.
If your query is of the form
SELECT *
FROM Table
WHERE (#SearchDate BETWEEN #StartDate AND #EndDate) AND Id=#Id
(which yours appears to be), then it will return the correct values from the db as long as the dates are being specified correctly.
Can you show the code where you're actually attempting to use the SqlConnection that you're opening in the posted code?

Related

Protecting rows depending on specific (today) date

I want to code my Google Sheets to check ("scan") active sheet to find a date that is "today" - and then, depending on the day, protect all columns in that row (row in witch it found todays date), so that only owner can change it (protect from everyone else).
With the help of the forum i found some "solutions", but cant get to make it work. I think there is a problem with for loop (just prediction).
Script should check for today date, read how many colmuns are active and lock the row(s) with today + all previous dates. I'm still missing the protection to lock all the rows with ownership rights only and ofcourse to work :)
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('MY SHEET');
function lockRanges() {
var dateRange = ss.getRange(2, 1, ss.getLastRow()-2, 1);
var curDate = Utilities.formatDate(new Date(), "GMT+1", "dd/M/YYYY");
var val = dateRange.getDisplayValues();
var row;
var col;
var end = ss.getLastRow();
//Find last active column
for (var y = 0; y <= ss.getLastColumn(); y++) {
col = y + 1;
}
//Loop through all rows
for(var x = 0; x <= end; x++){
if(val[x][0]> curDate){
row = x;
break;
}
}
var protection = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE)
if(protection.length > 0){
var range = ss.getRange(2, 1, row, col);
protection[0].setRange(range);
}
else{
ss.getRange(2, 1, row, col).protect();
}
}

Unable to set date values in SAP B1 matrix combobox

I am trying to set values in a matrix combobox but I cannot be able to set the first value of date to that combobox. It shows blank and when I select a date, it does not fill the field anyway.
The values I get from the DB are as follows:
Here is my code below including binding the combobox field to a userdatasource:
_expDate = _form.DataSources.UserDataSources.Add("iV_15", SAPbouiCOM.BoDataType.dt_DATE, 100);
oIColumns = oIMatrix.Columns;
_colExpDate = oIColumns.Item("iV_15");
_colExpDate.DataBind.SetBound(true, "", "iV_15");
The below code runs when there is a lost focus change event to the item selection field:
#region Item Change Event Expiry dates
_cmbExpDate = (SAPbouiCOM.ComboBox)oIMatrix.Columns.Item("iV_15").Cells.Item(pVal.Row).Specific;
int count = _cmbExpDate.ValidValues.Count;
if (count > 0)
{
_expDate.ValueEx = "";
for (int j = 0; j <= count - 1; j++)
_cmbExpDate.ValidValues.Remove(0, SAPbouiCOM.BoSearchKey.psk_Index);
}
var expDates = (from oi in _db.OITMs
join ob in _db.OBTNs
on oi.ItemCode equals ob.ItemCode
where ob.ItemCode == _itemNo.ValueEx && oi.OnHand > 0
orderby ob.ExpDate
select new
{
ExpDate = ob.ExpDate
}).Distinct().ToList();
if (expDates.Count > 0)
{
foreach (var item in expDates)
_cmbExpDate.ValidValues.Add(item.ExpDate?.ToString(), item.ExpDate?.ToString());
_cmbExpDate.Select(0, SAPbouiCOM.BoSearchKey.psk_Index);
_expDate.ValueEx = _cmbExpDate.Value;
}
#endregion
What could be wrong. Is there a better way to achieve what I need in SAP B1?
as a test try a different data type for your:
_expDate = _form.DataSources.UserDataSources.Add("iV_15", SAPbouiCOM.BoDataType.dt_DATE, 100);
test it with: SAPbouiCOM.BoDataType.dt_LONG_TEXT
you can also try just selecting the value on the combo, instead of setting uds as well.

Get Payment dates in a list

I have a payment check application, in that I get 2 strings:
String contractBegin = "01-01-2018";
String contractEnd = "31-12-2018";
Now every payment must be done the last Friday of the month. I need to calculate those dates and place it in a list or array.
Is there any optimal way to do that using the Java 8 nice features?
I started here:
String contractBegin = "01-01-2018";
String contractEnd = "31-12-2018";
LocalDate contractStart = LocalDate.parse(contractBegin, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
LocalDate contractStop = LocalDate.parse(contractEnd, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
System.out.println(contractStart);
System.out.println(contractStop);
List<LocalDate> payCheck= new ArrayList<>();
for (int i = 0; i < args.length; i++) {
payCheck.add(...) ??
}
I am not sure about your args array. But If you want to get every last friday of month between the contract start and end date. I would do as follow :
String contractBegin = "01-01-2018";
String contractEnd = "31-12-2018";
LocalDate contractStart = LocalDate.parse(contractBegin, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
LocalDate contractStop = LocalDate.parse(contractEnd, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
List<LocalDate> payCheck = new ArrayList<>();
LocalDate payCheckDate = contractStart;
while (payCheckDate.isBefore(contractStop)) {
payCheckDate = payCheckDate
.with(lastDayOfMonth())
.with(previousOrSame(DayOfWeek.FRIDAY));
payCheck.add(payCheckDate);
payCheckDate = payCheckDate.with(TemporalAdjusters.firstDayOfNextMonth());
}
payCheck.forEach(System.out::println);
This gives you every last friday of each month.
Another alternative to #gnostrenoff's answer is to use TemporalAdjusters.lastInMonth() method, which gives you the specified last day of week in the month:
// get the last Friday of the month
payCheckDate = payCheckDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY));
The rest of the while loop is the same as #gnostrenoff's answer.

Stored procedure wrong output

I have this stored procedure that returns data on a selected week, as in the Company, Name, Expected Work, and Work done between the 19/10/2015 and the 25/10/2015 (per example).
I have just recently added the Expected Work line and for some odd reason the output differs from one week to another, when the value should be the same.
Company1 - Christopher - 35 - 35 | On one week can give the following on another :
Company1 - Christopher - 350 - 35
I have just realized the value isn't correct when there is a value to Work done, if there is no work recorded the Expected Work has the right value.
Here is the procedure :
ALTER procedure [dbo].[spGetWeeklyActivityByEmployee]
#startDate date
, #endDate date
as
set datefirst 1 -- Monday
select
Company.Name as [Company]
, Employee.FirstName + ' ' + Employee.LastName as [Name]
, sum(UserActivity.Cost) as [Recorder Time]
, sum(Employee.ExpectedTime) as [Expected Time] // I have added this line, not sure if it's correct
from
dbo.Employee
inner join
dbo.Company on Company.CompanyId = Employee.CompanyId
left join
dbo.UserActivity on UserActivity.Login = Employee.Login
and UserActivity.CalendarDate >= #startDate
and UserActivity.CalendarDate <= #endDate
where
(Employee.EntranceDate is null
or YEAR(Employee.EntranceDate) < YEAR(#startDate)
or (YEAR(Employee.EntranceDate) = YEAR(#startDate)
and DATEPART(WEEK, Employee.EntranceDate) <= DATEPART(WEEK, #startDate)))
and (Employee.ExitDate is null
or YEAR(Employee.ExitDate) > YEAR(#endDate)
or (YEAR(Employee.ExitDate) = YEAR(#endDate)
and DATEPART(WEEK, Employee.ExitDate) >= DATEPART(WEEK, #endDate)))
group by
Company.Name, Employee.FirstName + ' ' + Employee.LastName
return 0
Am I missing something? Is the way I retrieve Expected Time wrong?
EDIT :
Here is the part in the code where I save the information in an array :
// create and open a connection object
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
conn.Open();
// 1. create a command object identifying
// the stored procedure
SqlCommand cmd = new SqlCommand("spGetWeeklyActivityByEmployee", conn);
// 2. set the command object so it knows
// to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("#startDate", wk1));
cmd.Parameters.Add(new SqlParameter("#endDate", wk2));
// execute the command
rdr = cmd.ExecuteReader();
string[] tab_company = new string[31]; // Don't mind the sizes
string[] tab_name = new string[31];
string[] tab_expectedtime = new string[31];
string[] tab_rectime = new string[31];
int counter;
counter = 0;
while (rdr.Read())
{
tab_company[counter] = rdr["Company"].ToString();
tab_name[counter] = rdr["Name"].ToString();
tab_expectedtime[counter] = rdr["Expected Time"].ToString();
tab_rectime[counter] = rdr["Recorder Time"].ToString();
counter++;
}
Perhaps the change in value comes from here?
Just take away the SUM() from Employee.ExpectedTime and add this to your GROUP BY

Difference between datepickers except sundays in infopath

How to get the no of days between two date picker controls in info path except sundays?
If It is possible let me know.
Thanks in advance.........
Using custom code you can do it easily. In this case I'm calculating the number of days (except Sundays) between a given date and today's date.
var navigator = this.MainDataSource.CreateNavigator();
string startDate = navigator.SelectSingleNode("/my:myFields/my:date_start", NamespaceManager).Value;
DateTime startDateTime = DateTime.ParseExact(startDate, "yyyy-MM-dd", null);
DateTime today = DateTime.Today;
int count = 0;
while (startDateTime > today)
{
today = today.AddDays(1);
if (today.DayOfWeek != DayOfWeek.Sunday)
{
count++;
}
}
I hope it helps