XML Query with a variable in WHERE - sql

I have this code that works well. But I want to have a variable to change its value in run time. I want the output xml file in C#.
declare #MySearch nvarchar(50)
set #MySearch='بودان'
SELECT ID, Family
FROM Table_1
where freetext(Family, #MySearch, LANGUAGE 1025)
FOR XML RAW ('Employee'), ROOT ('Employees'), ELEMENTS XSINIL;
EDITED:
I ran this code and got this error:
Null or empty full-text predicate.
I want the output xml file in C#.
declare #MySearch nvarchar(50)
--set #MySearch=N'بودان'
SELECT ID, Family
FROM Table_1
where freetext(Family, #MySearch, LANGUAGE 1025)
FOR XML RAW ('Employee'), ROOT ('Employees'), ELEMENTS XSINIL;

The "N" makes the difference, and you need it twice...
Try this:
DECLARE #v1 VARCHAR(10)='بودان';
DECLARE #v2 VARCHAR(10)=N'بودان';
DECLARE #nv1 NVARCHAR(10)='بودان';
DECLARE #nv2 NVARCHAR(10)=N'بودان';
SELECT #v1,#v2,#nv1,#nv2;
The result
????? ????? ????? بودان
Only the very last attempt will show what you need...
The reason: A normal string SET #v='MyString' is not handled as UNICODE
It is neither enough to declare the variable as NVARCHAR nor is it enough to store a unicode literal like N'SomeText'.
EDIT:
After long disucussion in comments the final sentence to solve the issue was this:
Of course you must be connected with the DB to do this!
What ever you want to with your database, first you need an opened connection.

Related

Temp variable used in select Query

I tried to retrieve data from the table using a temp variable. The temp variable returns correct data but when tried to use it in Query it is not returning correct data set.
I have tried retrieving data using hard coded temp value in the query, it works fine. Can anyone help me out to find the issue here.?
Below is my code I have tried
Declare #tempwordFinal varchar(50)
select #tempwordFinal = ''''+'%'+'The Big Bang'+'%'+''''
select #tempwordFinal --here the output is - '%The Big Bang%'
SELECT * from MasterProgram where ProgramTitle like #tempwordFinal --not working
SELECT * from MasterProgram where ProgramTitle like '%The Big Bang%' -- working
Because #tempwordFinal variable has single quotes at the start and end. So it expects the data in ProgramTitle column to have single quotes at the start and end. Except the wildcards whatever present inside the variable will be considered as data that's why it is failing.
select #tempwordFinal --here the output is - '%The Big Bang%'
^ ^
Try this way
Declare #tempwordFinal varchar(50)
select #tempwordFinal = '%The Big Bang%'
select 1 where 'The Big Bang' like #tempwordFinal
When you use variables for varchar datatype we don't need single quotes. Single quotes are required only when you hard code the string constants
The problem was with your (escaped) extra apostrophes. Like this ''''. You don't need those unless you are looking for words in the database which explicitly contain apostrophes. The corrected code looks like this:
Declare #tempwordFinal As Varchar(50);
Set #tempwordFinal = '%The Big Bang%';
Select #tempwordFinal; -- %The Big Bang%
SELECT * from MasterProgram where ProgramTitle like #tempwordFinal;

SQL Server Select XML Column Based on Content by User Input Values

I am developing an sql server 2012 based application.
I am a newbie to SQl server. But the requirement is to use it.
One of the table I am using contains an XML Datatype column. However the data containing in that column may vary as per the xml element. The only thing in common is the root: For instance this is a sample data:
<Tags>
<key1>Value1</key1>
<key2>Value2</key2>
<key3>Value3</key3>
<key4>Value4</key4>
<key5>Value5</key5>
<key6>Value6</key6>
</Tags>
What I want to do is to query the whole table and fetch records that will match a specific key and a specific values sent by the user.
Please assist me.
Well it sounds like you need to use some variables to build an XQuery, yes? So, assuming you build a stored procedure or something which takes a pair of string arguments for key and value you could use the following example I've knocked up in SQL Fiddle so you can try it out.
DECLARE #key nvarchar(20)
DECLARE #value nvarchar(20)
SET #key = N'key5'
SET #value = N'Value5'
SELECT
TagValue = T1.xmlcol.value('(/Tags/*[local-name()=sql:variable("#key")])[1]', 'varchar(10)')
FROM
dbo.T1
WHERE
T1.xmlcol.exist('/Tags/*[local-name()=sql:variable("#key")][text() = "Value5"]') = 1

Stored procedure parameter with XML query in MSSQL gives "argument must be string literal"

I'm trying to query a table with a column which is xml data with the query and value functions. When using regular string literals it's all okay, but if I put that in a stored procedure and try to use variables it doesn't work.
I suppose I'm not using the correct datatype, but after some searching I can't figure out what datatype the query function wants.
Example:
table contains
| Id | xmldata |
| 1 | <data><node>value</node></data> |
now, using the select query
select id
from table
where xmldata.query('/data/node').value('.', 'VARCHAR(50)') = 'value'
gets me the data I want. But, if I use this in a stored procedure and use a parameter #xpath varchar(100) and pass that to the query method as xmldata.query(#xpath)
i get the error
The argument 1 of the xml data type method "query" must be a string literal.
I guess varchar(100) is not correct, but what datatype can I use that would make MSSQL happy?
Update:
Okay, so. Apparently you can't pass a parameter to the query method "just like that", but one can use the sql:variable in conjunction with local-name to work a part of it out. So, for instance, this will work
declare #xpath VarChar(100)
set #xpath='node'
select objectData.query('/data/*[local-name() = sql:variable("#xpath")]')
.value('.', 'varchar(100)') as xmldata
from table
and value is selected in the column xmldata. But(!) it requires that the root node is the first value in the query function. The following will not work
declare #xpath VarChar(100)
set #xpath='/data/node'
select objectData.query('*[local-name() = sql:variable("#xpath")]')
.value('.', 'varchar(100)') as xmldata
from table
notice how the query path is "moved up" to the variable. I will continue my investigations..
A literal is the opposite of a variable. The message means that you cannot pass a variable as the first argument to query.
One way around that is dynamic SQL:
declare #sql varchar(max)
set #sql = 'select id from table where xmldata.query(''' + #path +
''').value(''.'', ''VARCHAR(50)'') = ''value'''
exec #sql
As you can see, dynamic SQL does not result in very readable code. I would certainly investigate alternatives.
EDIT: Your suggestion of local-name() works for node names.
declare #nodename varchar(max)
set #nodename = 'node'
...
where xmldata.query('//*[local-name()=sql:variable("#nodename")]')
.value('.', 'varchar(50)') = 'value'
There doesn't seem to be an equivalent for paths.

How to get Sql Server XML variable into TEXT column

I need to update an XML document stored in a Microsoft SQL Server database, however the vendor of the product chose to store the XML in a TEXT column.
I've been able to extract the TEXT into an XML-type variable and perform the update I need on the xml within this variable, but when I try to UPDATE the column to push the change back to the database, I run into trouble.
Looking through the documentation it appears that it's not possible to simply CAST/CONVERT an XML type variable to insert it into a TEXT column, but I would think there is some way to extract the xml "string" from the XML-type variable and UPDATE the column using this value.
Any suggestions are appreciated, but I would like to keep the solution pure SQL that it can be run directly (no C# custom function, etc.); just to keep the impact on the database minimal.
(note: isn't it a bit absurd that you can't just CAST XML as TEXT? I'm just saying...)
Casting the XML as VARCHAR(MAX) works.
declare #xml xml
declare #tblTest table (
Id int,
XMLColumn text
)
insert into #tblTest
(Id, XMLColumn)
values
(1, '<MyTest><TestNode>A</TestNode></MyTest>')
set #xml = '<MyTest><TestNode>A</TestNode><TestNode>B</TestNode></MyTest>'
update #tblTest
set XMLColumn = cast(#xml as varchar(max))
where Id = 1
select Id, XMLColumn from #tblTest

Accessing text fields in a stored procedure and insert to another table

I am trying to access a “text” type and inserting that value into another table viw a stored procedure. I’ve tried to cast it, convert it, but nothing works.
My code looks somethings like this:
Declare #Critique varchar(max), #Feedback varchar(max)
…
…
…
SELECT #Critique = CAST(comments as varchar(max)), #Feedback = CAST(public_critique as varchar(max)) FROM ASCO_vEXTERNAL_REVIEW_APPLICATIONS_LIST WHERE wf_task_assignment_id = #WfTaskAssignmentIDP1
– comments and public_critique are defined as text in view (also tried with table) ASCO_vEXTERNAL_REVIEW_APPLICATIONS_LIST
…
…
…
insert into WF_TASK_ASSIGNMENT_REVIEW (wf_task_assignment_review_id, wf_task_assignment_id, grantee_project_id, comments, public_critique) values (#NewID1, #WfTaskAssignmentIDP2, #GranteeProjectID, #Critique, #Feedback)
Can you please help me with this as soon as possible. I would really appreciate this.
Thanks,
Harish
I'm assuming that the WF_TASK_ASSIGNMENT_REVIEW is the one containing the text column you're trying to write into.
The text type is now deprecated in SQL 2005 and 2008. If at all possible try and upgrade the WF_TASK_ASSIGNMENT_REVIEW table to use the nvarchar(max) type instead.
If not, the only way is to use the WRITETEXT statement to write into the target column, in a loop (since WRITETEXT has an upper limit). See the WRITETEXT statement example in the SQL Server docs.
Your question is not sound good to understand .
Dont use text ,it wont support in many cases like where ,group by etc , so try use varchar
This is just an example
Declare #Critique varchar(max)
set #Critique = (select public_critique from ASCO_vEXTERNAL_REVIEW_APPLICATIONS_LIST
where convert(varchar(50), wf_task_assignment_id ) =#WfTaskAssignmentIDP1)