Dynamic SQL - Update Column by Prepending A Current Column - sql-server

I am trying to populate a column that is to represent an Internal URL that directs the user to a specific document. The document ID, DOC_ID, is already populated in the Table. I would like to populate the column by prepending a base URL to the Document ID. I do not know how to to do this dynamically and am getting some errors referring to the parameters of CONCAT(), issue being it is understanding it to be a string rather than the column value. My code is as follows:
SET #Insert_DRS_URL_SQL = 'UPDATE'
+ ' '
+ QUOTENAME(#TBL)
+ ' '
+ 'SET DRS_URL = CONCAT(#URLBASE'
+ ','
+ 'DOC_ID'
+ ')'
EXECUTE sp_executesql #Insert_DRS_URL_SQL;
UPDATE
#URLBASE = 'http://blah/blah/blah/id='
DRS_URL is the column I wish to populate.
Basically I need DRS_URL = #BASEURL + DOC_ID

Related

Retrieve value of a column after update?

I update a counter (no autoincrement ... not my database ...) with this FDQuery SQL:
UPDATE CountersTables
SET Cnter = Cnter + 1
OUTPUT Inserted.Cnter
WHERE TableName = 'TableName'
I execute FDQuery.ExecSQL and it works: 'Cnter' is incremented.
I need to retrieve the new 'Counter' value but the subsequent command
newvalue := FDQuery.FieldByName('Cnter').AsInteger
Fails with error:
... EDatabaseError ... 'CountersTables: Field 'Cnter' not found.
What is the way to get that value?
TFDQuery.ExecSQL() is meant for queries that don't return records. But you are asking your query to return a record. So use TFDQuery.Open() instead, eg:
FDQuery.SQL.Text :=
'UPDATE CountersTables' +
' SET Cnter = Cnter + 1' +
' OUTPUT Inserted.Cnter' +
' WHERE TableName = :TableName';
FDQuery.ParamByName('TableName').AsString := 'TableName';
FDQuery.Open;
try
NewValue := FDQuery.FieldByName('Cnter').AsInteger;
finally
FDQuery.Close;
end;
If the database you are connected to does not support OUTPUT, UPDATE OUTPUT into a variable shows some alternative ways you can save the updated counter into a local SQL variable/table that you can then SELECT from.
You have also the RETURNING Unified support Ok, doc only shows INSERT SQL but UPDATE works too.
And I should use a substitution variable for tablename

Create a joined Key-Value in LinqToSql

I have a GridView binded to LinqToSql-DataSource. The DataSource is Multiple-Join. I need unique Key-Values for the Grid. But all PrimaryKeys from the Tables could exist double or not because of left joins.
I have solved the problem in a pure sql-statement. There i create a ID for the TableRows by joining two PrimaryKeys an connecting with a "-". I need one of the IDs for later working with TableRows, the other could be null.
So I do in SQL-Statement:
select CAST(mitgliedschaft.id as varchar(MAX)) + '-' + CAST(ISNULL(funktion.id, '') as varchar(MAX)) as id from ...... inner join ...... etc
I need the CASTS for not producing Calculating with the "-" and the ISNULL-Function because the second ID could be Null.
Now I have to transfer this part of the scenario into Linq-Statement. I tried like this:
...
...
select new
{
...
id = mitgliedschaft.id.ToString() + "-" + (funktion.id == null ? 0 : funktion.id).ToString()
...
});
But didn't get it running in that way. Can someone help me concatenating an ID with "-" and an ID that can be NULL? If it is NULL it should be an empty String or Null-Digit or whatever.
got it now:
select new
{
id = (mitgliedschaft.id.ToString() + "-") + (funktion.id.ToString() ?? "0")
}

How to filter data in VBA?

I am working on a AddIn which is based on VBA. I import data from XML file. I want to apply filter on that data. I don't know how can I store and organize data.
XML File:
<?xml version="1.0"?>
<TestClass>
<TestObject>
<Site>Facebook</Site>
<Name>ABC</Name>
<URL>https://www.facebook.com/ABC/</URL>
</TestObject>
<TestObject>
<Site>Facebook</Site>
<Name>XYZ</Name>
<URL>https://www.facebook.com/XYZ/</URL>
</TestObject>
<TestObject>
<Site>Twitter</Site>
<Name>ABC</Name>
<URL>https://www.twitter.com/ABC/</URL>
</TestObject>
<TestObject>
<Site>Facebook</Site>
<Name>XYZ</Name>
<URL>https://www.twitter.com/XYZ/</URL>
</TestObject>
</TestClass>
Here is my code.
Set oXMLFile = CreateObject("Microsoft.XMLDOM")
XMLFileName = "C:\Users\abc\Desktop\TestFiles\TestData.xml"
oXMLFile.Load (XMLFileName)
Set Sites = oXMLFile.SelectNodes("TestClass/TestObject/Site/text()")
Set Names = oXMLFile.SelectNodes("TestClass/TestObject/Name/text()")
Set URLs = oXMLFile.SelectNodes("TestClass/TestObject/URL/text()")
Public SiteArray(100) As String
Public NameArray(100) As String
Public URLArray(100) As String
For i = 0 To (Sites.Length - 1)
SiteArray(i) = Sites(i).NodeValue
NameArray(i) = Names(i).NodeValue
URLArray(i) = URLs(i).NodeValue
Next
Now I don't know how to get list of Name where Site is Facebook. I also want to get list of URL of Twitter.
Can anybody please suggest me mechanism for filtering in above case?
Based on what you've said you want, I've amended your code and added comments to explain what I'm doing:
Set oXMLFile = CreateObject("Microsoft.XMLDOM")
XMLFileName = "C:\Users\abc\Desktop\TestFiles\TestData.xml"
oXMLFile.Load (XMLFileName)
Set Sites = oXMLFile.SelectNodes("TestClass/TestObject/Site/text()")
Set Names = oXMLFile.SelectNodes("TestClass/TestObject/Name/text()")
Set URLs = oXMLFile.SelectNodes("TestClass/TestObject/URL/text()")
Public myArray() As String ' declare array as dynamic so we can amend its size
ReDim myArray(6,0) ' reset it to be 2 dimensional
For i = 0 To (Sites.Length - 1)
myArray(0,i) = Sites(i).NodeValue ' Column 1 of the array contains Sites
myArray(1,i) = Names(i).NodeValue ' Column 2 of the array contains Names
myArray(2,i) = URLs(i).NodeValue ' Column 3 of the array contains URLs
myArray(3,i) = URLs(i).NodeValue ' Column 4 of the array contains URLs
myArray(4,i) = URLs(i).NodeValue ' Column 5 of the array contains URLs
myArray(5,i) = URLs(i).NodeValue ' Column 6 of the array contains URLs
myArray(6,i) = URLs(i).NodeValue ' Column 7 of the array contains URLs
ReDim Preserve myArray(6, UBound(myArray,2)+1) ' increase the size of the array dynamically to include an extra "row" of data
Next
' Now you can loop through and search for anything you want, like so:
For i = 0 to UBound(myArray, 2) ' loop through all the "rows" of the array
If Instr(LCase(myArray(0,i)), "facebook") > 0 Then ' If the site contains facebook
myName = myArray(1, i) ' returns the associated name for the Site
myURL = myArray(2, i) ' returns the associated URL for the Site
' Do whatever you need with this info then let the loop continue through the rest of the rows or use an Exit For statement to break the loop
End If
Next

T-SQL: how to update a rows that require some processing?

Let's say I have a table MessagingTemplates and a column [Subject]. Text in the column is of the following format
Operations Portal - Task proposed
Operations vendor - Task rejected
Resources Portal - Late Task
All the values in that column have the above format. I'd like to write a stored procedure that will change the text to
[CompanyName] - Task proposed - [proposedDate]
[CompanyName] - Task rejected - [proposedDate]
[CompanyName] - Late Task - [proposedDate]
I'm thinking about something like
UPDATE MessagingTemplates
SET [Subject] = '[CompanyName] - ' + [Subject] + ' - [proposedDate]'
WHERE MessageName IN ('TaskProposed, TaskRejected') -- There are many more ...
Obviously, before updating I need to remove everything that comes before -
UPDATE:
It looks like I need more processing because for some row there are more than one -. In those cases, I need to retrieve only the text after the last -.
How do I do that?
If this is a one way trip you could simple preprocess Subject:
UPDATE MessagingTemplates
SET Subject = RIGHT(#subject, LEN(#subject) - CHARINDEX('-',#subject,1) + 2)
and then run the query you have:
UPDATE MessagingTemplates
SET Subject = CompanyName + Subject + ' - ' + proposedDate
WHERE MessageName IN ('TaskProposed, TaskRejected') -- There are many more
assuming the CompnayName and proposedDate are actually other field so he table
EDIT: You comment clarifies your intend so it easy to use the quoted text as above.
UPDATE MessagingTemplates
SET Subject = '[CompanyName]' + Subject + ' - [proposedDate]'
WHERE MessageName IN ('TaskProposed, TaskRejected') -- There are many more
You can of course do it all in one update.
UPDATE MessagingTemplates
SET Subject = '[CompanyName]'
+ RIGHT(#subject, LEN(#subject) - CHARINDEX('-',#subject,1) + 2)
+ ' - [proposedDate]'
WHERE MessageName IN ('TaskProposed, TaskRejected') -- There are many more
But if may have multiple ' - ' and want to key of the last you need to mix in REVERSE()
UPDATE MessagingTemplates
SET Subject = '[CompanyName]'
+ RIGHT(#subject, CHARINDEX('-',REVERSE(#subject),1) + 2)
+ ' - [proposedDate]'
WHERE MessageName IN ('TaskProposed, TaskRejected') -- There are many more
UPDATE MessagingTemplates
SET [Subject] = '[CompanyName] ' + SUBSTRING([Subject],
CHARINDEX('-', SUBJECT), 100)
+ ' - [proposedDate]'
WHERE MessageName IN ( 'TaskProposed, TaskRejected' ) -- There are many more ...

update query with xml sql server 2008

I am having problem in updating database from xml and dynamic query.
Exec('UPDATE ' + #DbInstance + 'dbo.tblAcademic
SET tblacademic.RollNo = XMLAcademic.Item.value(''#RollNo'', ''VARCHAR(50)''),
tblacademic.Board = XMLAcademic.Item.value(''#Board'', ''VARCHAR(150)''),
tblacademic.PassingYear = XMLAcademic.Item.value(''#PassingYear'', ''VARCHAR(10)''),
tblacademic.Semester = XMLAcademic.Item.value(''#Semester'', ''VARCHAR(5)''),
tblacademic.MarksObt = XMLAcademic.Item.value(''#MarksObt'', ''varchar(9)''),
tblacademic.MaxMarks = XMLAcademic.Item.value(''#MaxMarks'', ''int'')
FROM ''' + Convert(varchar, #XMLEducationalDetail) + '''.nodes(''/root/row'') AS XMLAcademic(Item)
WHERE tblacademic.AcademicID = XMLAcademic.Item.value(''#AcademicID'', ''int'')')
This is showing error at Convert function and without convert function there is also execution error showing xml to nvarchar error.

Resources