I have a GridView that will have multiple search options.
Call Date
Start_Time (between two time values)
Call_Time
AgentID
Phone
What they want is all of these options available to search by with a single search button.
What I am having trouble with is how to build the query to be dynamic so if they only search by one option it will search by that, if they search by three of the above it will still provide accurate results.
Here is the Query so far:
SELECT *, 'file://///server/folder/' + replace(call_date, '/', '') + '/'
+ qa_status + '.vox' as url FROM [JM_NSC_Recordings] WHERE ([areacode] + [phone] = #phone)
Phone = [areacode] + [phone] // #phone
Start Time = between [start_time] and [start_time] #starttime
Call Time = [call_time] // #calltime
AgentID = [tsr] // #agentid
Call Date = [call_date] // #calldate
All of these fields in the database are VARCHAR
I used a StringBuilder for same type of advance search in which there are multiple parameters.
StringBuilder stmt=new StringBuilder();
stmt.AppendLine("select * from table where ");
if(phone not blank)
stmt.AppendLine("phone=89754654 and ");
else
stmt.AppendLine("true and ");
if(agentid not blank)
stmt.AppendLine("agentid=89754654 and");
else
stmt.AppendLine("true and ");
else
stmt.AppendLine("true ");
and so on try it will work
Related
I'm trying to search the max ID in the database, then increment it by 1 for each new entry as shown below:
var query2 = dbb.Database.SqlQuery<patient_visit>("SELECT MAX(CAST(SUBSTRING(pvid, 3, 10) AS int)) FROM patient_visit");
if (query2 != null)
{
objDetails.pvid = query2.ToString();
objDetails.pvid += 1;
objDetails.pvid = "PV" + objDetails.pvid;
}
string sql = "INSERT INTO patient_visit (pvid,paid) " +
"VALUES('" + objDetails.pvid + "', '" + paid + "')";
But when i try to insert it in the database, it gives out error
An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: String or binary data would be truncated.
I've tried running the query in SQL Server and checked the value of 'pvid', it is 10 so after i include 'PV' to the integer pvid, it should be 12. So it should be fine, but why did i get that error? Please can anyone help me?
[Key]
[MaxLength(20), MinLength(12)]
public string pvid { get; set; }
When i replace the pvid with hard code ID, it works just fine. Why is this happening?
P/S: I know its not advisable to simply concatenate the input data with the query, but i've also tried querying using parameterized query but it gives same error.
string sql = "INSERT INTO patient_visit (pvid,paid) " +
"VALUES(#pvid, #paid)";
List<SqlParameter> parameterList = new List<SqlParameter>();
parameterList.Add(new SqlParameter("#pvid", objDetails.pvid));
parameterList.Add(new SqlParameter("#paid", paid));
SqlParameter[] parameters = parameterList.ToArray();
dbb.Database.ExecuteSqlCommand(sql, parameters);
Check the Field length of the column you are trying to put the data into.
I have had this problem before where the column was varchar(10) and I was trying to concatenate two char strings of 6 characters each. Making them 12 characters long. 2 longer than the target field.
Your problem might be similar.
I'm trying to migrate from ASP.NET WebForms to MVC and have used this example
which worked fine using SQL Server 2008 Express hosted on an Azure VM. However once I modified the SQL from the "Step 6: Get the Data from the Repository" section of the tutorial:
public class MessagesRepository
{
readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
public IEnumerable<Messages> GetAllMessages()
{
var messages = new List<Messages>();
using (var connection = new SqlConnection(_connString))
{
connection.Open();
using (var command = new SqlCommand(#"SELECT [MessageID], [Message], [EmptyMessage], [Date] FROM [dbo].[Messages]", connection))
{
command.Notification = null;
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
messages.Add(item: new Messages { MessageID = (int)reader["MessageID"], Message = (string)reader["Message"], EmptyMessage = reader["EmptyMessage"] != DBNull.Value ? (string) reader["EmptyMessage"] : "", MessageDate = Convert.ToDateTime(reader["Date"]) });
}
}
}
return messages;
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
MessagesHub.SendMessages();
}
}
}
Which I changed the SQL to this:
#"SELECT [AssignedToUser], [Status], [RequestID] FROM [dbo].[Notifications] WHERE AssignedToUser IS NOT NULL AND Status IS NOT NULL AND RequestID IS NOT NULL AND AssignedToUser = 'Kyle G' AND Status = 'Red'
Which worked fine but when I wanted to get only notifications stamped with today's date and appended my SQL:
AND CAST(TimeStatusChange AS DATE) = CONVERT(date, getdate())
Or even this:
AND TimeStatusChange >= (GetDate() - 1)
It fails to update unless you refresh the page. Any ideas friends?
Note-TimeStatusChange is a datetime field.
I converted the current day and database field "TimeStatusChange" as such:
SELECT convert(varchar(25), TimeStatusChange, 120) AS TimeStatusChange, [Id],[AssignedToUser], [Status], [RequestID] FROM [dbo].[Notifications] WHERE AssignedToUser IS NOT NULL AND Status IS NOT NULL AND RequestID IS NOT NULL AND AssignedToUser = 'Kyle G' AND Status = 'Red' AND convert(varchar(25), getdate(), 112) = convert(varchar(25), TimeStatusChange, 112) ORDER BY TimeStatusChange DESC
It should be noted that the issue remains and is not that the SQL when run VS 2015 or SSMS does not work it does. It also works on a page refresh of the MVC page. It does not push the new record to the page in real time without a page refresh.
Here is the results in SSMS using Convert for both the TimeStatusChange and getdate() objects:
In other words if I do this (Essentially an "If 1==1" test):
SELECT TimeStatusChange FROM [dbo].[Notifications] WHERE convert(varchar(25), TimeStatusChange, 112) = convert(varchar(25), TimeStatusChange, 112)
SignalR Updates the page upon INSERT of new record.
If I change it to compare the DB field to today's date as strings:
SELECT TimeStatusChange FROM [dbo].[Notifications] WHERE convert(varchar(25), TimeStatusChange, 112) = convert(varchar(25), getdate(), 112)
SignalR no longer updates the page on INSERT new record unless I refresh it. The SQL works it just breaks SignalR from updating the page without a refresh.
If I do the opposite If 1==1 test by comparing today's date to itself as a string:
SELECT TimeStatusChange FROM [dbo].[Notifications] WHERE convert(varchar(25), getdate(), 112) = convert(varchar(25), getdate(), 112)
This also breaks SignalR from updating the page UNLESS I refresh the page. The clue seems to be a problem with:
convert(varchar(25), getdate(), 112)
Breaking SignalR, not the SQL. Perhaps this is too difficult to troubleshoot without having the full solution available.
To answer your question " Do you have a suggestion as to how to get today's date as just the date and no time as a date?"
Here is how you would convert the dates:
SELECT CONVERT(VARCHAR(10),GETDATE(),112),CONVERT(VARCHAR(10),GETDATE(),111),CONVERT(VARCHAR(10),GETDATE(),110)
and the results:
I finally got it (Thanks to Kamran & Dan for hints). I do not understand why this worked but by passing the current date into the SQL statement as a string as opposed to using getdate() or DATEADD in SQL made it work! Why is beyond my pay grade.
Here is the working code (yes I will parameterize it!)
string dateof = DateTime.Today.ToString("MM/dd/yyyy");
connection.Open();
using (var command = new SqlCommand(#"SELECT [Id],[AssignedToUser], [Status], [RequestID] FROM [dbo].[Notifications] WHERE '" + dateof + "' = convert(varchar(25), TimeStatusChange, 101) ORDER BY TimeStatusChange DESC", connection))
I'm calling a stored procedure via direct SQL from X++, and I can't figure out how to get the integer return value from it. 0 is good, -1 is bad.
// Login to SQL DB
loginProperty = new LoginProperty();
loginProperty.setServer('localhost');
loginProperty.setDatabase('SQL_DB');
odbcConnection = new OdbcConnection(loginProperty);
statement = odbcConnection.createStatement();
/*
#in_customer_id INT
,#status INT
,#dlvmode NVARCHAR(25)
,#dlvmodedesc NVARCHAR(50)
,#tracking_id NVARCHAR(50)
,#note NVARCHAR(MAX)
,#modified SMALLDATETIME = null
,#override_email NVARCHAR(200) = null
*/
sqlStatement = strfmt(' EXEC pr_send_status_email ' +
' %1,' + // CustomerId
' %2,' + // Status
' %3,' + // DlvMode
' %4,' + // DlvMode description
' %5,' + // Tracking #
' %6,' + // Note
' %7' // DateTime
, 160308
, 2
, sqlSystem.sqlLiteral("FD1")
, sqlSystem.sqlLiteral("Fed Ex overnight")
, sqlSystem.sqlLiteral("1ZABCDEF")
, sqlSystem.sqlLiteral("Note Here")
, sqlSystem.sqlLiteral(DateTimeUtil::utcNow()));
sqlStatementExecutePermission = new SqlStatementExecutePermission(sqlStatement);
sqlStatementExecutePermission.assert();
//BP deviation documented
resultSet = statement.executeQuery(sqlStatement);
//info(strfmt("%1", statement.executeUpdate(sqlStatement))); // I Tried this too
CodeAccessPermission::revertAssert();
if (resultSet.next()) // Errors here
info(strfmt("Return: %1", resultSet.getInt(1)));
The executeUpdate returns an updated row count; otherwise 0 for SQL statements that return nothing.
The executeQuery returns an instance of the ResultSet class, but calling a stored procedure is not a select, so you break the contract.
What you are trying to do is not supported.
You may use C# as glue code or use the C# types directly using .NET CLR Interop.
I've looked around everywhere, but I can't seem to find exactly what I'm trying to do. It should be fairly simple...
I have a db table set up like this:
var db = Ti.Database.open('playerInfo.db');
db.execute('CREATE TABLE IF NOT EXISTS playersTable (id INTEGER PRIMARY KEY, name TEXT NOT NULL, "50" INTEGER, "25" INTEGER )');
I have two buttons with an assigned value of 25, and 50, respectively. Each button has a "value" key, where I assign their values. I am trying to accomplish three things:
When a button is pressed, find the column of corresponding value.
increase the value of this column by 1.
Retrieve the new value and console log it.
This is what my code looks like when a button is pressed:
var rows = db.execute("SELECT '" + button.value + "' FROM playersTable WHERE name= '" + owner + "'");
var imagesString = rows.fieldByName(button.value);
Ti.API.debug(imagesString)
This is all in a click event listener where the variable "owner" is passed in as a string.
This is the error I get:
message = "Attempted to access unknown result column 25";
I don't have too much experience with sql, so I'm not sure what I'm doing right and what I'm doing wrong. Any help is appreciated!
Thanks.
I'm not sure quite exactly what the problem is, but the following works for me. Note that the "?" variable substitution syntax makes sure that the values are quoted properly for MySQL:
button = e.source;
db = Titanium.Database.open('test');
var rows = db.execute("SELECT * FROM playersTable WHERE name= ?", "foo");
// Theoretically this should be returning a single row. For other results,
// we would loop through the result set using result.next, but here just check if
// we got a valid row.
if (rows.isValidRow()) {
var imagesString = rows.fieldByName(button.value);
var id = rows.fieldByName('id');
imagesString = imagesString + 1;
Ti.API.info("id = " + id + " val = " + imagesString);
// The ? substitution syntax doesn't work for column names, so we
// still need to stick the button value into the query string.
db.execute('UPDATE playersTable set "' + button.value +'"= ? where id = ?', imagesString, id);
}
else
{
Ti.API.info("Row not found.");
}
db.close();
If you get the row not found error, it's possible your data isn't getting inserted properly in the first place. Here's how I inserted my test row for player "foo":
db.execute('insert into playersTable (name, "50", "25") values (?,?,?)', 'foo', 0, 0);
I think this should solve your problem. Let me know if this doesn't work for you.
I'm writing a Windows service that will poll my IMAP4 inbox for emails from clients and create new Cases in Salesforce based on them.
Sometimes emails come in with a Case reference code in the subject. Ex: "[ ref:00FFwxyz.500FFJJS5:ref ]". I'd like to assign such emails to the existing Case identified by the code rather than create a new one.
My questions is: Is there a definitive formula for extracting a unique Case identifier from the ref code? I've seen a few formulas that do the reverse, but they all look like guesswork: Blog post on KnowThyCloud.com, Force.com Discussion Board thread.
Found a decent enough solution. I was wrong in calling the post on KnowThyCloud.com guesswork. In the right context it works fine.
My solution is to create a new custom field on the Case record of type "Formula (Text)". The field's value is the formula mentioned in the blog post:
TRIM(" [ ref:" + LEFT( $Organization.Id, 4) + RIGHT($Organization.Id, 4) +"."+ LEFT( Id, 4) + SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(Id, RIGHT( Id, 4), ""), LEFT( Id, 4), ""), "0", "") + RIGHT( Id, 4) + ":ref ] ")
Now the value of the custom field for each Case record is the same as the reference Id in emails and I can simply query for it with the Salesforce API.
I implemented urig's solution and it works well.
Here is an Apex code solution that locates the Case without this field.
String emailSubject = 'FW: Re: RE: order 36000862A Case: 00028936 [ ref:00D7JFzw.5007Ju10k:ref ]';
String caseNumber = null;
/*
Extract the text after ref: and before the period. Could use this to locate the organization.
In the text after the period and before the :ref split into a 4 digit number and remaining number.
Insert 0's to get ref id.
*/
String patternString = '.*ref:(.{8}).(.{4})(.+):ref.*';
Pattern thePattern = Pattern.compile(patternString);
Matcher matcher = thePattern.matcher(emailSubject);
if (matcher.matches()) {
String caseId = matcher.group(2) + '000000' + matcher.group(3);
Case[] matchingCases = [Select CaseNumber from Case where Id = :caseId];
if(matchingCases.size() == 1) {
Case theCase = matchingCases[0];
caseNumber = theCase.CaseNumber;
}
}
I have modified Jan's code snippet above in order to support the new reference string containing underrscores (e.g. _00DC0PxQg._500C0KoOZS).
String patternString = '.*ref:(.{11}).(.{5})(.+):ref.*';
Pattern thePattern = Pattern.compile(patternString);
Matcher matcher = thePattern.matcher(emailSubject);
if (matcher.matches()) {
String caseId = matcher.group(2) + '00000' + matcher.group(3);
system.debug('### '+caseId);
Case[] matchingCases = [Select CaseNumber from Case where Id = :caseId];
if(matchingCases.size() == 1) {
Case theCase = matchingCases[0];
caseNumber = theCase.CaseNumber;
}
}