Is there a way in SQL to update an existing value to be himself with a new value ?
For example :
I have a value "992", and I want to add "135" so it will be "992135".
I tried doing this :
string sql1 = "UPDATE [Table1] SET OldValue = OldValue " + ValueToAdd;
But it just sums it up (ends up to be 992+135 = 1127).
Thanks
You are looking either for string concatenation or arithmetic, depending on the type of the column. The standard concatenation operator is ||, although many databases support the concat() function:
UPDATE [Table1]
SET OldValue = CONCAT(OldValue, ValueToAdd);
Or, as arithmetic:
UPDATE [Table1]
SET OldValue = OldValue * 1000 + ValueToAdd;
Related
I am attempting to update one column of a table based on data present in other records of the same table. All records either have the same date in the "CurrentDate" field or are null. I want to change those with null values to be the same as the rest of the fields.
Here is my code, but I am getting a syntax error:
Public Sub RiskVisual()
Dim db As DAO.Database
Set db = CurrentDb
---
DoCmd.RunSQL "UPDATE Hold3 SET CurrentDate = (SELECT CurrentDate FROM Hold3 LIMIT 1) WHERE CurrentDate IS NULL;"
End Sub
Thanks in advance for your help.
In MS Access the "TOP 1" works better than "LIMIT 1". You will also want to specify when seeking for the top 1 that the top 1 that is not null. Try something like this:
UPDATE Hold3 SET Hold3.CurrentDate = (SELECT TOP 1 Hold3.CurrentDate FROM Hold3 WHERE (((Hold3.CurrentDate) Is Not Null))) WHERE (((Hold3.CurrentDate) Is Null));
I am trying to update multiple rows at once (SQL Server 2005). Previously I was updating a single row with this query:
UPDATE dbo.My_Users
SET MyUserId = #MyUserId
WHERE EmailID = #EmailId
Now #EmailId will have comma-separated EmailIds.
How can I modify the script to update multiple rows? I have seen some examples which make use of UNION ALL. But they are mostly to insert multiple records without where clause.
A similar question was answered in Parameterize an SQL IN clause
The same idea can be applied here:
declare #EmailIds varchar = '|email1#test.com|email2#test.com|';
UPDATE dbo.My_Users SET MyUserId=#MyUserId WHERE #EmailIds LIKE '%|' + EmailID + '|%';
Though this does not contain a comma-separated list, the delimiter could easily be changed to a pipe-character. The caveat here is, the more data that exists in the table and the more email addresses that are in the #EmailIds list, the slower (much slower) this query can become.
Using C#, I would actually recommend the second example in the above-mentioned question where the list is expanded to create a query similar to:
UPDATE dbo.My_Users SET MyUserId=#MyUserId WHERE EmailID IN (#email1, #email2);
C# to implement (a modified version of the example in the question above):
string[] emails = new string { "email1#test.com", "email2#test.com" };
string sql = "UPDATE dbo.My_Users SET MyUserId=#MyUserId WHERE EmailID IN ({0});"
string[] emailParams = emails.Select((s, i) => "#email" + i.ToString()).ToArray();
string inClause = string.Join(",", emailParams);
using (SqlCommand cmd = new SqlCommand(string.Format(sql, inClause))) {
for(int i = 0; i < emailParams.Length; i++) {
cmd.Parameters.AddWithValue(emailParams[i], emails[i]);
}
}
You could use dynamic SQL
exec('UPDATE dbo.My_Users SET MyUserId = ' + cast(#MyUserId as varchar) + ' WHERE EmailID in (' + #EmailIds + ')')
I am attempting to query an MS Access DB with C#
Static query is -
Select FieldID , CDGroups.CDGroupID , Priority
from Fields , CDGroups
where Fields.CDGroupID = CDGroups.CDGroupID
and Fields.FieldID in ('f1','f2','f3')
order by Priority
I need to replace f1,f2.. FieldID from fieldIdList(List<string> fieldIdList) which contains all these fields
How can I go about it?
The correct way would be to use SQL parameters.
To do this, you need to loop through your list and create one parameter per list item - in the SQL string and in your query's list of SQL parameters.
Take a look at this answer to a similar question:
How to pass sqlparameter to IN()?
var listId= string.Join(",", fieldIdList.Select(m => string.Format("'{0}'", m)));;
then
"Field.FieldID in (" + listId+ ")
I used following code:
StringBuilder sb = new StringBuilder();
foreach (string fieldId in fieldIdList)
{
sb.Append("'" + fieldId + "',");
}
string fieldList = sb.ToString().TrimEnd(',');
string queryString =
"Select FieldID , CDGroups.CDGroupID , Priority from Fields , CDGroups where Fields.CDGroupID = CDGroups.CDGroupID and Fields.FieldID in (" + fieldList + ") order by Priority";
Try this query -
SELECT CDGroupID FROM fields
WHERE FieldID IN ('f1', 'f2', 'f3')
GROUP BY CDGroupID
HAVING(COUNT(DISTINCT FieldID)) >= 3
It will show a list of CDGroupID that have 'f1','f2' and 'f3' at least. If you want to show ones that have just 'f1','f2' and 'f3', then change WHERE condition to 'HAVING(COUNT(DISTINCT FieldID)) >= 3'.
SAMPLE CODE:
Dim sql As String = "SELECT * FROM " + tblName + " WHERE needsTranslation = 'True' AND dataText LIKE " & "'" & alpha & "%" & "'" & " ORDER BY dataText;"
da = New SqlDataAdapter(sql, strConnection)
OP:
I would like to create a SQL query that returns all records when the first letter of a string matches my variable. I am coding this in an ASP.net code behind page in vb.net.
SELECT * FROM " + tblName + " WHERE textData = ' & alpha & "
In this exmample textData is a string of text and alpha is a single letter a through z or A through Z.
I don't need the criteria to be case sensitive, but I do need only the first letter of textData to match alpha.
I have tested the LIKE comparator and it does not return all records that begin with alpha.
What is the best way to do this? Any and all help will be appreciated.
thanks again,
The LIKE operator is what you'd want to use, but you have to use the % wildcard character like so:
SELECT * FROM MyTable WHERE textData LIKE 'a%'
SQL has sub-string operator SUBSTR() or SUBSTRING()
select * from tableName where substr( textData ) in ( 'A', 'B', 'C', ... );
I couldn't add to the comments on one of the other posts, but I'll strongly second the need to use a parameterized query for these reasons (you can include usage of the like operator with the wildcard % like the other answer correctly summarized to answer your question):
It will protect you from making mistakes with single quotes, especially if the user enters a search string that includes them
(they will cause your query to fail).
It protects you from SQL injection exploits. Example, a user were able to input the value of the variable "alpha" in the above
example they could enter something like:
'; DELETE FROM ;
If the user you were using had excessive database rights, they could
wreak all kinds of havoc (or they could potentially get access to
data they shouldn't have access to).
String sql = "select * from file_repo_index where id in (?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString (1, toCommaSeparatedList(repoIdList));
ResultSet result = ps.executeQuery();
public static String toCommaSeparatedList(Collection col);
I have to use the query as
select * from file_repo_index where id in ( 1,2,3,4 )
But it gives following error in executeQuery() statement
java.sql.SQLException: Conversion failed when converting the nvarchar value '213304,213305,213307' to data type int.
I can use it like
String sql = "select * from file_repo_index where id in ("+toCommaSeparatedList(repoIdList)+")";
Statement ps = conn.createStatement();
ResultSet result = ps.executeQuery(sql);
But I want to use the PrepareStatment method. How can I do it. ??
You should create your prepare statement placeholders based on your values, for instance:
String sql = "select * from file_repo_index where id in (";
//append ?, in above sql in a loop
//Then prepare statement.
This will involve a bit of extra coding, but i think this is the only way to force using PreparedStatement.
If You want to use IN keyword then inside the brackets you have to put like
('213304','213305','213307')
as seperate variables and dont combine in a single "single quotes the entire values" and also in the select statement
String sql = "select * from file_repo_index where id in ("+toCommaSeparatedList(repoIdList)+")";
Change the double quotes to single and try
('+ toCommaSeparatedList(repoIdList) +')";