Showing posts with label select. Show all posts
Showing posts with label select. Show all posts

Thursday, March 29, 2012

Forecasting in analysis tab cannot view

Hi I installed the add-in for excel data mining but when i try to select a table, in the tab of analyze, dont have any properties. please help me.

carlos of southamerica

Did you select a cell within a table?

Do you see "Table Tools" above the ribbon?

Do you see "Analyze" and "Design" ribbons? (they are usually the last 2 ribbons)

If all answers are yes, what do you see in the Analyze ribbon?

ForEachLoop Container and Variables

Hi Guys

I am trying to do the following and am quite new to SSIS.

I have to select a dataset from a database on server A, check if it exists on server B and perform an Update or Insert dependant on the existence.

I have created a SQL task to do the Select from server A with the results set passed to a variable of Vendors. I have added a ForEach Loop container with an enumerator of Foreach ADO Enumerator and the source variable is set to Vendors.

I have created 2 variables in the Foreach Loop called Code and Supplier - both as strings - as there are 2 fields from the initial Select that need to be passed to the final Update/ Insert.

I have then created another SQL task insert the Foreach which will perform the Update/Insert.

obviously when I run it at the moment it performs the Update/ Insert but just adds the rows with both Code and Supplier as NULL.

having looked at a couple of examples in books I have i know i need to add something in the Expressions of the Update/Insert SQL task but it is here i get a bit lost.

Which of the properties from the drop down do i need to use to map the variables against?

Any help would be massively appreciated asI am tearing my hair out!

Thanks

Scott

Hi Scott,

We're all still learning SSIS.

It sounds like you're most of the way there.

There are a couple ways to approach this solution. The simplest way, from what I understand from your post, is to use placeholders and parameters in your Update/Insert statements. If you already have the Code and Supplier variables defined, you could perform an insert using an Execute SQL Task with something similar to the following code:

Code Snippet

INSERT INTO Vendors

(Code, Supplier)

VALUES(?, ?)

You could then supply Parameters:

Code Snippet

VariableName Direction DataType ParameterName ParameterSize

User::Code Input Int 0 -1

User::Supplier Input VarChar 1 -1

This would substitute the question marks in the SQL Statement property with the values contained in your variables.

Hope this helps,

Andy

|||

Scott,

Any special reason for not using a dataflow with a lookup transform to detect if the rows exists(update) or not (insert). That is by far a pretty common practice in these scenarios.

|||

Hi Rafael

Still new to this (and database stuff as a whole) and am going on someone elses advice!

I have looked at your suggestion and have got as far as the following:

OLEDB Source with a SQL select statement to return the data required

Look Up transform to look up the 2 columns from the Select against the destination table

After that I am a bit lost. I guess i have to add a OLEDB destination but do I do it to a table or a SQL Command?

thanks again

Scott

|||

I think you are on the right track. I would add an OLE DB Destination against the destination table.

Keep in mind you have to tweak the lookup to 'redirect' errors. Lookup will treat the no matches as errors; hence will be send to the error output of the component (red arrow). Then you have to connect the error output of the Lup to the input of the destination.

Now the updates; every row going to the green output of the L.up is an existing/to-updated row. Here you have 2 options; use an OLE DB Commnad to update the row in the destination table; or send those rows to an estiging table (yes a seconf OLE DB Destination) and then back in control flow use an Execute SQl task to do a 1 time update. The advantage of the second method is performance. the Update runs 1 time updating all the required rows. The First one will perform an update for every row passing trhough; wich depending on the volume of data can be performance killer; the good thing is that you don't need a second table.

This thread has some examples

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1211340&SiteID=1

Monday, March 26, 2012

Foreach File Enumerator -

I am trying to use the Foreach File Enumerator and map it to a user variable.

I select a folder in the colletion.

I use *.* for file name.

I left the default value for retrive file name.

I assigned it to my user variable ( data type string)

I am get the following error "The element cannot be found in a collection"

I am sure that I have at lest 10 file in the folder.

Can anyone tell me why I get the error?

I found out what my problem was

I had to assign a value to the variable.

The Foreach File Enumerator did not set the value when i mapped it to the variable.

I had to type in a value for the variable after I created it.

forcing remote evaluation of like filters with linked servers

i have server1
server 2 is linked to server1
server 3 is linked to server1
all sql2005
on server1 i go
select foo from [server2].[db].[dbo].table where bar like '%ff%'
union all
select foo from [server3].[db].[dbo].table where bar like '%ff%'
by looking at the execution plan I can see that the remote selects have no
filter on them and that the filtering is applied locally by server1. this is
of course extremely inefficient.
The docs say that if I say thet the provider has sql like capability then
the query planner 'might' consider asking the remote server to do the like
processing.
I did that (even though it seems redundant since server1 knows that this is
another sql sevrer database).
What other magic buttons do I have to pressHi Paul
Using OPENQUERY would allow you to filter remotely.
John
"paul moore" wrote:
> i have server1
> server 2 is linked to server1
> server 3 is linked to server1
> all sql2005
> on server1 i go
> select foo from [server2].[db].[dbo].table where bar like '%ff%'
> union all
> select foo from [server3].[db].[dbo].table where bar like '%ff%'
> by looking at the execution plan I can see that the remote selects have no
> filter on them and that the filtering is applied locally by server1. this is
> of course extremely inefficient.
> The docs say that if I say thet the provider has sql like capability then
> the query planner 'might' consider asking the remote server to do the like
> processing.
> I did that (even though it seems redundant since server1 knows that this is
> another sql sevrer database).
> What other magic buttons do I have to press
>
>|||thanks - works great
seems like the 'normal' query processor should do it automatically though -
defaulting to the most inefficient way is surprising
"John Bell" wrote:
> Hi Paul
> Using OPENQUERY would allow you to filter remotely.
> John
> "paul moore" wrote:
> > i have server1
> > server 2 is linked to server1
> > server 3 is linked to server1
> > all sql2005
> >
> > on server1 i go
> > select foo from [server2].[db].[dbo].table where bar like '%ff%'
> > union all
> > select foo from [server3].[db].[dbo].table where bar like '%ff%'
> >
> > by looking at the execution plan I can see that the remote selects have no
> > filter on them and that the filtering is applied locally by server1. this is
> > of course extremely inefficient.
> >
> > The docs say that if I say thet the provider has sql like capability then
> > the query planner 'might' consider asking the remote server to do the like
> > processing.
> > I did that (even though it seems redundant since server1 knows that this is
> > another sql sevrer database).
> >
> > What other magic buttons do I have to press
> >
> >
> >|||Hi
I think if you were not using like you would be ok, but I haven't tested it!
John
"paul moore" wrote:
> thanks - works great
> seems like the 'normal' query processor should do it automatically though -
> defaulting to the most inefficient way is surprising
> "John Bell" wrote:
> > Hi Paul
> >
> > Using OPENQUERY would allow you to filter remotely.
> >
> > John
> >
> > "paul moore" wrote:
> >
> > > i have server1
> > > server 2 is linked to server1
> > > server 3 is linked to server1
> > > all sql2005
> > >
> > > on server1 i go
> > > select foo from [server2].[db].[dbo].table where bar like '%ff%'
> > > union all
> > > select foo from [server3].[db].[dbo].table where bar like '%ff%'
> > >
> > > by looking at the execution plan I can see that the remote selects have no
> > > filter on them and that the filtering is applied locally by server1. this is
> > > of course extremely inefficient.
> > >
> > > The docs say that if I say thet the provider has sql like capability then
> > > the query planner 'might' consider asking the remote server to do the like
> > > processing.
> > > I did that (even though it seems redundant since server1 knows that this is
> > > another sql sevrer database).
> > >
> > > What other magic buttons do I have to press
> > >
> > >
> > >

Forcing leading zero

How can I force a number to have leading zeros ?

select '123456' from dual;

I have try using TO_NUMBER :

select TO_NUMBER('123456','00999999') from dual;

But it doesn't seems to work. It will conserve the leading zeros but I want to add some.Hehe.. sorry I get it, I just have to use TO_CHAR instead of TO_NUMBER|||Thats the way it is :)

Greetz

Manfred Peter
(Alligator Company)
http://www.alligatorsql.com

Friday, March 23, 2012

Forcing a set number of result rows in a query

I'm trying to select 5 rows of data from a query. Sometimes there is less than 5 rows of data in the result set.

Is there a way to FORCE a return of 5 rows - even if they don't exist? For example, returning some text such as "No Data" or NULL in the result set?

What I'm doing to return 5 rows of data:

Select top 5 *

From MyTable

I need help modifying this query to make sure I always get 5 rows of data.

Thanks!

There is no pre-defined settings available but you do something below,

Code Snippet

Create table #Data(

Id int,

Name varchar(100)

)

Insert Into #Data Values(1,100)

Insert Into #Data Values(2,100)

Insert Into #Data Values(3,100)

Select Top 5 * From

(

Select Id, Name from #Data

Union ALL

Select NULL, NULL

Union ALL

Select NULL, NULL

Union ALL

Select NULL, NULL

Union ALL

Select NULL, NULL

Union ALL

Select NULL, NULL

)

as Data

Order By Case When Id is NULL Then 1 Else 0 End , ID

|||

Code Snippet

CREATE TABLE #temp (test int)

INSERT INTO #temp SELECT 1

INSERT INTO #temp SELECT 2

INSERT INTO #temp SELECT 3

DECLARE @.counter as int

set @.counter = (SELECT COUNT(*) from #temp)

SELECT * FROM #temp

WHILE @.counter < 5

BEGIN

INSERT INTO #temp SELECT NULL

SET @.counter = @.counter + 1

END

SELECT * FROM #temp

DROP TABLE #temp

Adamus

|||Thanks for the prompt replies - both of these replies were helpful and answered my question!

forceseek performance and cost...

Hi,

I have just run the 2 queries from the BOL to test the forceseek option:

USE AdventureWorks;

GO

SELECT*

FROM Sales.SalesOrderHeader AS h

INNERJOIN Sales.SalesOrderDetail AS d

ON h.SalesOrderID = d.SalesOrderID

WHERE h.TotalDue > 100

AND(d.OrderQty > 5 OR d.LineTotal < 1000.00);

GO

SELECT*

FROM Sales.SalesOrderHeader AS h

INNERJOIN Sales.SalesOrderDetail AS d WITH(FORCESEEK)

ON h.SalesOrderID = d.SalesOrderID

WHERE h.TotalDue > 100

AND(d.OrderQty > 5 OR d.LineTotal < 1000.00);

GO

When I take a look at the execution plan, the first query has a cost of 20% and the forceseek take 80% of the total cost.

Also the number of logical read jump from 1238 to 66194!!!

So the forceseek option has a bad impact on the query.

The BOL says if there is a lot of IO, using the forceseek can provide better performance... but in this case its not so clear...

can you explain more in detail when its better to use the forceseek?

Thanks.

The cost increases,but if you look, the index change of clustered index scan to clustered index seek and if you compare the estimated I/O cust and estimated CPU Cost you can see the differences.The number reduce....

|||

Actually this is expected behavior. We have approx 30k rows of Order Header with approx 120k with order lines. What you tell SQL Server in the latter query, is to ignore the fact that we are retrieving all the rows, and still use a lookup instead of a scan. So what SQL Server does (on your demand) is to take each and every order one by one and lookup the corresponding order lines. If you looked carefully at the execution plan, you'ld see that the merge join was replaced with a inner loop join. The latter is more efficient if you lookup only a few values, but when you lookup all the values a merge join is way much faster.

As I understand the FORCESEEK its a way of forcing seeking in the index the few times that SQL Server believes it has to read more or less the whole table, while it actually is going to retrieve just a few rows.

Anybody is free to correct me if I'm wrong on this one.


Edit: That said, when I run a trace it actually seems that the last query is the faster, I would guess that is since all the data already are in memory.

|||

Hints are there to be used when the optimizer produces a less than optimal plan and, despite over two decades of effort, query optimizers still can't get the 100% best plan 100% of the time.

So what is FORCESEEK intended to deal with? The optimizer is always working with imperfect data about the values in the table. And when you start doing a join using multiple predicates that include operators such as "<" and ">" its ability to accurately estimate the number of rows that will be touched declines. Particularly true if you don't have up to date statistics on some of the columns, or if you encounter one of the rare instances where the histograms don't capture enough information to do accurate estimates. Historically (dating back to the System R research project) if you don't have statistics that indicate otherwise then an operator such as ">" is considered to be true for 1/3 of the data. Thus ORing two such conditions would lead to an assumption that 2/3 of the table was going to be retrieved which clearly would lead to a scan over a seek. This is a grand oversimplification of how things work in this day and age, but the basics help you understand why the optimizer might choose the wrong plan. It might think that 2/3 of the rows must be touched while you know that based on the actual data it is more like .01%. The bottom line being, there are cases where the optimizer will think that a scan offers the best performance but where human knowledge of the data makes it clear that a seek is the better alternative.

Using the optimizer's own statistics to see if FORCESEEK is better or not is a mistake. The reason the optimizer didn't choose the seek strategy on its own is that it estimated it would take a lot more I/O and rejected that strategy. So when you use FORCESEEK and look at the estimates what you see are the (incorrect) estimates that the optimizer saw when it considered this strategy on its own. You just can't use that data, you need to look at the actual performance of the query.

Hal

sql

forceseek performance and cost...

Hi,

I have just run the 2 queries from the BOL to test the forceseek option:

USE AdventureWorks;

GO

SELECT*

FROM Sales.SalesOrderHeader AS h

INNERJOIN Sales.SalesOrderDetail AS d

ON h.SalesOrderID = d.SalesOrderID

WHERE h.TotalDue > 100

AND(d.OrderQty > 5 OR d.LineTotal < 1000.00);

GO

SELECT*

FROM Sales.SalesOrderHeader AS h

INNERJOIN Sales.SalesOrderDetail AS d WITH(FORCESEEK)

ON h.SalesOrderID = d.SalesOrderID

WHERE h.TotalDue > 100

AND(d.OrderQty > 5 OR d.LineTotal < 1000.00);

GO

When I take a look at the execution plan, the first query has a cost of 20% and the forceseek take 80% of the total cost.

Also the number of logical read jump from 1238 to 66194!!!

So the forceseek option has a bad impact on the query.

The BOL says if there is a lot of IO, using the forceseek can provide better performance... but in this case its not so clear...

can you explain more in detail when its better to use the forceseek?

Thanks.

The cost increases,but if you look, the index change of clustered index scan to clustered index seek and if you compare the estimated I/O cust and estimated CPU Cost you can see the differences.The number reduce....

|||

Actually this is expected behavior. We have approx 30k rows of Order Header with approx 120k with order lines. What you tell SQL Server in the latter query, is to ignore the fact that we are retrieving all the rows, and still use a lookup instead of a scan. So what SQL Server does (on your demand) is to take each and every order one by one and lookup the corresponding order lines. If you looked carefully at the execution plan, you'ld see that the merge join was replaced with a inner loop join. The latter is more efficient if you lookup only a few values, but when you lookup all the values a merge join is way much faster.

As I understand the FORCESEEK its a way of forcing seeking in the index the few times that SQL Server believes it has to read more or less the whole table, while it actually is going to retrieve just a few rows.

Anybody is free to correct me if I'm wrong on this one.


Edit: That said, when I run a trace it actually seems that the last query is the faster, I would guess that is since all the data already are in memory.

|||

Hints are there to be used when the optimizer produces a less than optimal plan and, despite over two decades of effort, query optimizers still can't get the 100% best plan 100% of the time.

So what is FORCESEEK intended to deal with? The optimizer is always working with imperfect data about the values in the table. And when you start doing a join using multiple predicates that include operators such as "<" and ">" its ability to accurately estimate the number of rows that will be touched declines. Particularly true if you don't have up to date statistics on some of the columns, or if you encounter one of the rare instances where the histograms don't capture enough information to do accurate estimates. Historically (dating back to the System R research project) if you don't have statistics that indicate otherwise then an operator such as ">" is considered to be true for 1/3 of the data. Thus ORing two such conditions would lead to an assumption that 2/3 of the table was going to be retrieved which clearly would lead to a scan over a seek. This is a grand oversimplification of how things work in this day and age, but the basics help you understand why the optimizer might choose the wrong plan. It might think that 2/3 of the rows must be touched while you know that based on the actual data it is more like .01%. The bottom line being, there are cases where the optimizer will think that a scan offers the best performance but where human knowledge of the data makes it clear that a seek is the better alternative.

Using the optimizer's own statistics to see if FORCESEEK is better or not is a mistake. The reason the optimizer didn't choose the seek strategy on its own is that it estimated it would take a lot more I/O and rejected that strategy. So when you use FORCESEEK and look at the estimates what you see are the (incorrect) estimates that the optimizer saw when it considered this strategy on its own. You just can't use that data, you need to look at the actual performance of the query.

Hal

Wednesday, March 21, 2012

Force to date format MMDDYY

My sql :

SELECT....., date_ of_ shipment,.....

FROM......

WHERE.....

ORDER BY....

After that it will export to excel.

My problem: Some times I get a column of mixing date format MMDDYY and number.?


I have to format the whole excel column to get all date format.

My question: How can I write sql so it force the the result to be date format MMDDYY in excel? Where this clause in sql (where clause ?)

Thanks
Daniel

Code Snippet

select convert(varchar(8), getdate(), 1)

OR

select replace(convert(varchar(8), getdate(), 1), '/', '')

Depending on whether you want the slash separators or not.

Use code 101 instead of 1 in the Convert if you want 4 digit years.

|||

If my column name is date_of _shipment

Select convert (varchar(8), date_of_shipment,1) ?

Thnks

Daniel

|||

Right.

It will also lose it's name, so you may want to re-alias it.

Code Snippet

Select convert (varchar(8), date_of_shipment,1) AS date_of_shipment

|||

Thanks a millions. Look like it work great for what ever my excel column format.

Daniel

|||

I may need hour: min: second too

How about MMDDYYYYHHMMSS ?


Thanks
Daniel

Monday, March 12, 2012

FOR XML: date returned without timezone

I'm querying a table with a datetime field using SELECT ... FOR XML. The
dates are returned in the following format:
<updated>2006-01-04T11:52:52.403</updated>
Is there any possiblity to add the timezone information to it? The result
should look as follows:
<updated>2006-01-04T11:52:52.403Z</updated>
The SQL statements looks like
SELECT date AS updated
FROM articles FOR XML PATH('entry')
Best regards
MartinI found a solution:
CONVERT(VARCHAR, date, 126) + 'Z' AS updated
126 is the style code for the ISO8601 date representation, i.e. XML
representation.
"Martin Szugat" wrote:

> I'm querying a table with a datetime field using SELECT ... FOR XML. The
> dates are returned in the following format:
> <updated>2006-01-04T11:52:52.403</updated>
> Is there any possiblity to add the timezone information to it? The result
> should look as follows:
> <updated>2006-01-04T11:52:52.403Z</updated>
> The SQL statements looks like
> SELECT date AS updated
> FROM articles FOR XML PATH('entry')
> Best regards
> Martin

FOR XML: date returned without timezone

I'm querying a table with a datetime field using SELECT ... FOR XML. The
dates are returned in the following format:
<updated>2006-01-04T11:52:52.403</updated>
Is there any possiblity to add the timezone information to it? The result
should look as follows:
<updated>2006-01-04T11:52:52.403Z</updated>
The SQL statements looks like
SELECT date AS updated
FROM articles FOR XML PATH('entry')
Best regards
Martin
I found a solution:
CONVERT(VARCHAR, date, 126) + 'Z' AS updated
126 is the style code for the ISO8601 date representation, i.e. XML
representation.
"Martin Szugat" wrote:

> I'm querying a table with a datetime field using SELECT ... FOR XML. The
> dates are returned in the following format:
> <updated>2006-01-04T11:52:52.403</updated>
> Is there any possiblity to add the timezone information to it? The result
> should look as follows:
> <updated>2006-01-04T11:52:52.403Z</updated>
> The SQL statements looks like
> SELECT date AS updated
> FROM articles FOR XML PATH('entry')
> Best regards
> Martin

for xml to local variable

Is there a reason why the following does not work...
declare @.s varchar(1024)
set @.s = (select * from validTable for xml auto)
...assuming I know for a fact that the returned xml stream will fit inside my declared variable.
I suspect it's just the pre-compiler getting it's knickers in a knot over the * when this technically meets the requirements for setting a local variable.
... i think...
Does any one have any comments or ideas on how to achieve the same effect inside an SQL stored Proc.?
WR
Unfortunately, this can't be done in SQL Server 2000 - what actually gets
returned is a single column/single row resultset containing the XML stream.
The client-side components of SQLXML can extract that as a stream but
there's no way to do it in T-SQL.
In SQL Server 2005, you can use the xml data type to do what you're
suggesting.
Cheers,
Graeme
--
Graeme Malcolm
Principal Technologist
Content Master Ltd.
www.contentmaster.com
www.microsoft.com/mspress/books/6137.asp
"WildRide" <WildRide@.discussions.microsoft.com> wrote in message
news:06CEF1F3-F947-45B9-93BE-BE8FEF4E3DF6@.microsoft.com...
Is there a reason why the following does not work...
declare @.s varchar(1024)
set @.s = (select * from validTable for xml auto)
...assuming I know for a fact that the returned xml stream will fit inside
my declared variable.
I suspect it's just the pre-compiler getting it's knickers in a knot over
the * when this technically meets the requirements for setting a local
variable.
... i think...
Does any one have any comments or ideas on how to achieve the same effect
inside an SQL stored Proc.?
WR
|||sorry but i have testing this code with sqlserver 2000
and it doesent work
Cdlt
Query:
declare @.s varchar(1024)
set @.s = (select * from USERPROFILE for xml auto)
Result:
Server: Msg 170, Level 15, State 1, Line 2
Line 2: Incorrect syntax near 'xml'.

>--Original Message--
>Unfortunately, this can't be done in SQL Server 2000 -
what actually gets
>returned is a single column/single row resultset
containing the XML stream.
>The client-side components of SQLXML can extract that as
a stream but
>there's no way to do it in T-SQL.
>In SQL Server 2005, you can use the xml data type to do
what you're
>suggesting.
>Cheers,
>Graeme
>--
>--
>Graeme Malcolm
>Principal Technologist
>Content Master Ltd.
>www.contentmaster.com
>www.microsoft.com/mspress/books/6137.asp
>
>"WildRide" <WildRide@.discussions.microsoft.com> wrote in
message
>news:06CEF1F3-F947-45B9-93BE-BE8FEF4E3DF6@.microsoft.com...
>Is there a reason why the following does not work...
>declare @.s varchar(1024)
>set @.s = (select * from validTable for xml auto)
>...assuming I know for a fact that the returned xml
stream will fit inside
>my declared variable.
>I suspect it's just the pre-compiler getting it's
knickers in a knot over
>the * when this technically meets the requirements for
setting a local
>variable.
>... i think...
>Does any one have any comments or ideas on how to achieve
the same effect
>inside an SQL stored Proc.?
>WR
>
>.
>
|||"Boss Hog" <anonymous@.discussions.microsoft.com> wrote in message
news:74c001c4764f$9c4d6bb0$a301280a@.phx.gbl...
> sorry but i have testing this code with sqlserver 2000
> and it doesent work
It won't work because it isn't supported.
Bryant

for xml raw problem

Hi
I'm running a simple query with for xml raw on a table
one of columns in select clause here is of type text and stores xml
file itself.
The problem i'm facing is when I get this text back from this column I
get back unformatted xml
e.g
instead of getting <GPF> I get <GPF> etc
How do I get this column as formatted xml text ?
Thanks for help
Vishy>
> I'm running a simple query with for xml raw on a table
> one of columns in select clause here is of type text and stores xml
> file itself.
> The problem i'm facing is when I get this text back from this column I
> get back unformatted xml
> e.g
> instead of getting <GPF> I get <GPF> etc
> How do I get this column as formatted xml text ?
>
Hello
signs '<' and '>' are very important in XML because they show begin and end
of xml element, so when an element or attribute value has such signs it must
be changed into < and >. But when you open XML which contains such
substitution - using DOM or OPENXML in SQL you will get values with signs
'<', '>'. So I think that it sould not be a problem - siply try to process
XML which was generated and you will see that it has valid values of
elements/attributes.
I hope it helps,
Alwik|||Thanks Alwik for reply
I tried to create object on XmlDocument using LoadXml() method
it loads up the xml successfully but if I want to run any Xpath; it
fails
as <GPF> is not treated as <GPF> so I can't find GPF element
is there any work around?
Vishy|||Are you using SQL Server 2000 or 2005?
In the case of SQL Server 2000, you will have to use the explicit mode and
its !xml directive, if you want to have string data be inlined into the XML
structure.
In the case of SQL Server 2005, you can stick with the FOR XML RAW query,
but you need to cast the string data to XML in the select clause.
Best regards
Michael
"Vishy" <vishal.halbe@.gmail.com> wrote in message
news:1128445808.595093.141180@.g49g2000cwa.googlegroups.com...
> Thanks Alwik for reply
> I tried to create object on XmlDocument using LoadXml() method
> it loads up the xml successfully but if I want to run any Xpath; it
> fails
> as <GPF> is not treated as <GPF> so I can't find GPF element
> is there any work around?
> Vishy
>|||Thanks Michael for reply
I'm using SQL 2000
Vishy

for xml raw problem

Hi
I'm running a simple query with for xml raw on a table
one of columns in select clause here is of type text and stores xml
file itself.
The problem i'm facing is when I get this text back from this column I
get back unformatted xml
e.g
instead of getting <GPF> I get <GPF> etc
How do I get this column as formatted xml text ?
Thanks for help
Vishy
>
> I'm running a simple query with for xml raw on a table
> one of columns in select clause here is of type text and stores xml
> file itself.
> The problem i'm facing is when I get this text back from this column I
> get back unformatted xml
> e.g
> instead of getting <GPF> I get <GPF> etc
> How do I get this column as formatted xml text ?
>
Hello
signs '<' and '>' are very important in XML because they show begin and end
of xml element, so when an element or attribute value has such signs it must
be changed into < and >. But when you open XML which contains such
substitution - using DOM or OPENXML in SQL you will get values with signs
'<', '>'. So I think that it sould not be a problem - siply try to process
XML which was generated and you will see that it has valid values of
elements/attributes.
I hope it helps,
Alwik
|||Thanks Alwik for reply
I tried to create object on XmlDocument using LoadXml() method
it loads up the xml successfully but if I want to run any Xpath; it
fails
as <GPF> is not treated as <GPF> so I can't find GPF element
is there any work around?
Vishy
|||Are you using SQL Server 2000 or 2005?
In the case of SQL Server 2000, you will have to use the explicit mode and
its !xml directive, if you want to have string data be inlined into the XML
structure.
In the case of SQL Server 2005, you can stick with the FOR XML RAW query,
but you need to cast the string data to XML in the select clause.
Best regards
Michael
"Vishy" <vishal.halbe@.gmail.com> wrote in message
news:1128445808.595093.141180@.g49g2000cwa.googlegr oups.com...
> Thanks Alwik for reply
> I tried to create object on XmlDocument using LoadXml() method
> it loads up the xml successfully but if I want to run any Xpath; it
> fails
> as <GPF> is not treated as <GPF> so I can't find GPF element
> is there any work around?
> Vishy
>
|||Thanks Michael for reply
I'm using SQL 2000
Vishy

FOR XML Query

Hi Guys,
I am trying to understand the FOR XML EXPLICIT option and what I don't
understand is , how is the XML being generated , for example,
select 1 AS TAG,
NULL as PARENT,
NULL as [Customers!1!!element],
NULL as [Customer!2!!element]
from Customers
select 2 AS TAG,
1 as PARENT,
NULL as [Customers!1!!element],
NULL as [Customer!2!!element]
from Customers
both the above queries on Northwind returns 92 rows - When I union them a
(EVEN IF I DON'T SPECIFY FOR XML EXPLICIT) it returns only 2 rows !!! How
does this happen ? What's the trick here ?
Thanks!
You only have 2 distinct rows specified:
1 null null null
2 1 null null
if you select some data from the tables by specifying some column names you
will get more rows in the result. UNION eliminates duplicates so you're
down to only two rows.
This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm
"pSm" <pSm@.discussions.microsoft.com> wrote in message
news:697805DC-78EA-42E3-B970-97D7F86A2211@.microsoft.com...
> Hi Guys,
> I am trying to understand the FOR XML EXPLICIT option and what I
> don't
> understand is , how is the XML being generated , for example,
> ----
> select 1 AS TAG,
> NULL as PARENT,
> NULL as [Customers!1!!element],
> NULL as [Customer!2!!element]
> from Customers
> ----
> select 2 AS TAG,
> 1 as PARENT,
> NULL as [Customers!1!!element],
> NULL as [Customer!2!!element]
> from Customers
> both the above queries on Northwind returns 92 rows - When I union them a
> (EVEN IF I DON'T SPECIFY FOR XML EXPLICIT) it returns only 2 rows !!! How
> does this happen ? What's the trick here ?
> Thanks!
>
|||Also, note that for FOR XML, you should use UNION ALL that does not
eliminate duplicates.
There was an old article that Michael Conning and I write back in 99 that
explains the explicit mode (you should find it with a websearch). Or both
Books Online and the SQL Server 2005 whitepaper on MSDN about FOR XML should
be able to help.
HTH
Michael
"Roger Wolter[MSFT]" <rwolter@.online.microsoft.com> wrote in message
news:uGJCbTh9EHA.3416@.TK2MSFTNGP09.phx.gbl...
> You only have 2 distinct rows specified:
> 1 null null null
> 2 1 null null
> if you select some data from the tables by specifying some column names
> you will get more rows in the result. UNION eliminates duplicates so
> you're down to only two rows.
> --
> This posting is provided "AS IS" with no warranties, and confers no
> rights.
> Use of included script samples are subject to the terms specified at
> http://www.microsoft.com/info/cpyright.htm
> "pSm" <pSm@.discussions.microsoft.com> wrote in message
> news:697805DC-78EA-42E3-B970-97D7F86A2211@.microsoft.com...
>

For Xml Path, functions and UDF's

I have created a select statement to return using for xml path which works
without problem.
I now need to add into it the results of a UDF which relates to the data I
already have (parent - child stuff) but I'm running into problems doing this
.
If i include the complete sub query directly in the sql it works without any
issues, but if I take the sub select and put into into a table returning UDF
I get an error "Incorrect syntax near '.'." and the '.' is the parameter
passed to the UDF. The reason for looking at placing the sub-select in a UD
F
is that the same query needs to be included in 20+ sp's all returning Xml
using For Xml Path
I have included pseudo-SQL below showing examples
Anybody have any idea why the UDF won't work'
original sql that works
select a, b,c
from table1
for xml path ('item'), root('root')
modified that will work
select
t1.a,
t1.b,
t1.c,
(select t3.a, t2.e, t2.f
from table2 as t2
join table3 as t3 on t2.id = t3.id
where t3.a = t1.a
for xml path ('internal'), type
)
from table as t1
for xml path ('item'), root('root')
modified that won't work
select
t1.a,
t1.b,
t1.c,
(select u1.a, u1.e, u1.f
from dbo.UDF (t1.a) as u1
for xml path ('internal'), type
)
from table as t1
for xml path ('item'), root('root')Ok, just found the issue with the UDF in BOL so I understand why I can't pas
s
the parameter in, which is a shame.
Currently investigating creating a scalar UDF that will return xml to see if
thay works.
"Nathan" wrote:

> I have created a select statement to return using for xml path which work
s
> without problem.
> I now need to add into it the results of a UDF which relates to the data I
> already have (parent - child stuff) but I'm running into problems doing th
is.
> If i include the complete sub query directly in the sql it works without a
ny
> issues, but if I take the sub select and put into into a table returning U
DF
> I get an error "Incorrect syntax near '.'." and the '.' is the parameter
> passed to the UDF. The reason for looking at placing the sub-select in a
UDF
> is that the same query needs to be included in 20+ sp's all returning Xml
> using For Xml Path
> I have included pseudo-SQL below showing examples
> Anybody have any idea why the UDF won't work'
> original sql that works
> select a, b,c
> from table1
> for xml path ('item'), root('root')
> modified that will work
> select
> t1.a,
> t1.b,
> t1.c,
> (select t3.a, t2.e, t2.f
> from table2 as t2
> join table3 as t3 on t2.id = t3.id
> where t3.a = t1.a
> for xml path ('internal'), type
> )
> from table as t1
> for xml path ('item'), root('root')
>
> modified that won't work
> select
> t1.a,
> t1.b,
> t1.c,
> (select u1.a, u1.e, u1.f
> from dbo.UDF (t1.a) as u1
> for xml path ('internal'), type
> )
> from table as t1
> for xml path ('item'), root('root')|||Well after dispairing that I could resolve the issue and having to post on
the forum I've sorted it.
Final solution was to use a scalar UDF that took a parameter from the select
and returned a xml data type with the data in it which was then amalgamated
by For Xml Path correctly.
"Nathan" wrote:
> Ok, just found the issue with the UDF in BOL so I understand why I can't p
ass
> the parameter in, which is a shame.
> Currently investigating creating a scalar UDF that will return xml to see
if
> thay works.
> "Nathan" wrote:
>

For Xml Path, functions and UDF's

I have created a select statement to return using for xml path which works
without problem.
I now need to add into it the results of a UDF which relates to the data I
already have (parent - child stuff) but I'm running into problems doing this.
If i include the complete sub query directly in the sql it works without any
issues, but if I take the sub select and put into into a table returning UDF
I get an error "Incorrect syntax near '.'." and the '.' is the parameter
passed to the UDF. The reason for looking at placing the sub-select in a UDF
is that the same query needs to be included in 20+ sp's all returning Xml
using For Xml Path
I have included pseudo-SQL below showing examples
Anybody have any idea why the UDF won't work?
original sql that works
select a, b,c
from table1
for xml path ('item'), root('root')
modified that will work
select
t1.a,
t1.b,
t1.c,
(select t3.a, t2.e, t2.f
from table2 as t2
join table3 as t3 on t2.id = t3.id
where t3.a = t1.a
for xml path ('internal'), type
)
from table as t1
for xml path ('item'), root('root')
modified that won't work
select
t1.a,
t1.b,
t1.c,
(select u1.a, u1.e, u1.f
from dbo.UDF (t1.a) as u1
for xml path ('internal'), type
)
from table as t1
for xml path ('item'), root('root')
Ok, just found the issue with the UDF in BOL so I understand why I can't pass
the parameter in, which is a shame.
Currently investigating creating a scalar UDF that will return xml to see if
thay works.
"Nathan" wrote:

> I have created a select statement to return using for xml path which works
> without problem.
> I now need to add into it the results of a UDF which relates to the data I
> already have (parent - child stuff) but I'm running into problems doing this.
> If i include the complete sub query directly in the sql it works without any
> issues, but if I take the sub select and put into into a table returning UDF
> I get an error "Incorrect syntax near '.'." and the '.' is the parameter
> passed to the UDF. The reason for looking at placing the sub-select in a UDF
> is that the same query needs to be included in 20+ sp's all returning Xml
> using For Xml Path
> I have included pseudo-SQL below showing examples
> Anybody have any idea why the UDF won't work?
> original sql that works
> select a, b,c
> from table1
> for xml path ('item'), root('root')
> modified that will work
> select
> t1.a,
> t1.b,
> t1.c,
> (select t3.a, t2.e, t2.f
> from table2 as t2
> join table3 as t3 on t2.id = t3.id
> where t3.a = t1.a
> for xml path ('internal'), type
> )
> from table as t1
> for xml path ('item'), root('root')
>
> modified that won't work
> select
> t1.a,
> t1.b,
> t1.c,
> (select u1.a, u1.e, u1.f
> from dbo.UDF (t1.a) as u1
> for xml path ('internal'), type
> )
> from table as t1
> for xml path ('item'), root('root')
|||Well after dispairing that I could resolve the issue and having to post on
the forum I've sorted it.
Final solution was to use a scalar UDF that took a parameter from the select
and returned a xml data type with the data in it which was then amalgamated
by For Xml Path correctly.
"Nathan" wrote:
[vbcol=seagreen]
> Ok, just found the issue with the UDF in BOL so I understand why I can't pass
> the parameter in, which is a shame.
> Currently investigating creating a scalar UDF that will return xml to see if
> thay works.
> "Nathan" wrote:

FOR XML PATH nested query refer to parent variable

I have the following query:
Select BunCode as '@.BunCode', Min(TradingDate) as '@.TradingDate',
(Select ItemQty, TransactionSequenceNumber, GsiCode, RetalItemCode
FROM ods_TransmitFile WHERE BunCode = 1821
FOR XML PATH, TYPE)
FROM ods_TransmitFile
GROUP BY BunCode
ORDER BY BunCode
FOR XML PATH('BunCode'), ROOT('DM')
The query returns the correct structure however I would like the nested
query to refer to the '@.BunCode' of the parent query.
At present the nested results will always be for BunCode 1821. How can
I set ...WHERE BunCode = @.BunCode to equal the BunCode of the current
element?
Hope this makes sense?
Maybe by aliasing the tables? NOTE: *Untested*:
Select otf2.BunCode as '@.BunCode', Min(otf2.TradingDate) as '@.TradingDate',
(Select otf1.ItemQty, otf1.TransactionSequenceNumber, otf1.GsiCode,
otf1.RetalItemCode
FROM ods_TransmitFile otf1 WHERE otf1.BunCode = otf2.BunCode
FOR XML PATH, TYPE)
FROM ods_TransmitFile otf2
GROUP BY otf2.BunCode
ORDER BY otf2.BunCode
FOR XML PATH('BunCode'), ROOT('DM')
<justin.drerup@.gmail.com> wrote in message
news:1166543884.982800.201900@.t46g2000cwa.googlegr oups.com...
>I have the following query:
> Select BunCode as '@.BunCode', Min(TradingDate) as '@.TradingDate',
> (Select ItemQty, TransactionSequenceNumber, GsiCode, RetalItemCode
> FROM ods_TransmitFile WHERE BunCode = 1821
> FOR XML PATH, TYPE)
> FROM ods_TransmitFile
> GROUP BY BunCode
> ORDER BY BunCode
> FOR XML PATH('BunCode'), ROOT('DM')
> The query returns the correct structure however I would like the nested
> query to refer to the '@.BunCode' of the parent query.
> At present the nested results will always be for BunCode 1821. How can
> I set ...WHERE BunCode = @.BunCode to equal the BunCode of the current
> element?
> Hope this makes sense?
>
|||Thanks for your reply, I managed to get the solution working using
table aliases in a similar fashion to what you suggested.
|||Thanks for your reply, I managed to get the solution working using
table aliases in a similar fashion to what you suggested.

Friday, March 9, 2012

FOR XML PATH nested query refer to parent variable

I have the following query:
Select BunCode as '@.BunCode', Min(TradingDate) as '@.TradingDate',
(Select ItemQty, TransactionSequenceNumber, GsiCode, RetalItemCode
FROM ods_TransmitFile WHERE BunCode = 1821
FOR XML PATH, TYPE)
FROM ods_TransmitFile
GROUP BY BunCode
ORDER BY BunCode
FOR XML PATH('BunCode'), ROOT('DM')
The query returns the correct structure however I would like the nested
query to refer to the '@.BunCode' of the parent query.
At present the nested results will always be for BunCode 1821. How can
I set ...WHERE BunCode = @.BunCode to equal the BunCode of the current
element?
Hope this makes sense?Maybe by aliasing the tables? NOTE: *Untested*:
Select otf2.BunCode as '@.BunCode', Min(otf2.TradingDate) as '@.TradingDate',
(Select otf1.ItemQty, otf1.TransactionSequenceNumber, otf1.GsiCode,
otf1.RetalItemCode
FROM ods_TransmitFile otf1 WHERE otf1.BunCode = otf2.BunCode
FOR XML PATH, TYPE)
FROM ods_TransmitFile otf2
GROUP BY otf2.BunCode
ORDER BY otf2.BunCode
FOR XML PATH('BunCode'), ROOT('DM')
<justin.drerup@.gmail.com> wrote in message
news:1166543884.982800.201900@.t46g2000cwa.googlegroups.com...
>I have the following query:
> Select BunCode as '@.BunCode', Min(TradingDate) as '@.TradingDate',
> (Select ItemQty, TransactionSequenceNumber, GsiCode, RetalItemCode
> FROM ods_TransmitFile WHERE BunCode = 1821
> FOR XML PATH, TYPE)
> FROM ods_TransmitFile
> GROUP BY BunCode
> ORDER BY BunCode
> FOR XML PATH('BunCode'), ROOT('DM')
> The query returns the correct structure however I would like the nested
> query to refer to the '@.BunCode' of the parent query.
> At present the nested results will always be for BunCode 1821. How can
> I set ...WHERE BunCode = @.BunCode to equal the BunCode of the current
> element?
> Hope this makes sense?
>|||Thanks for your reply, I managed to get the solution working using
table aliases in a similar fashion to what you suggested.|||Thanks for your reply, I managed to get the solution working using
table aliases in a similar fashion to what you suggested.

FOR XML not working in a subquery

The following seems to work in SQL Server 2005, but I'm getting the
error 'Incorrect syntax near xml' when I run it in SQL Server 2000.

select a.accountid , (select street, city, state, zip from account b
where a.accountid =b.accountid for xml auto, elements) as xmldata
from account a

The idea is to return 2 columns:
accountid
xmldata (address as xml)

Assuming the fields are correct, any ideas on what the problem might be?(jonathaneggert@.hotmail.com) writes:

Quote:

Originally Posted by

The following seems to work in SQL Server 2005, but I'm getting the
error 'Incorrect syntax near xml' when I run it in SQL Server 2000.
>
>
select a.accountid , (select street, city, state, zip from account b
where a.accountid =b.accountid for xml auto, elements) as xmldata
from account a
>
The idea is to return 2 columns:
accountid
xmldata (address as xml)
>
Assuming the fields are correct, any ideas on what the problem might be?


The problem is simply that you try to achieve something which is not
possible in SQL 2000.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Well thanks for such a detailed explanation of the answer.

Why can't this be done in SQL Server 2000? It is a sub-query which I
have used extensively in SQL Server 2000--why the problem with FOR XML?

Erland Sommarskog wrote:

Quote:

Originally Posted by

(jonathaneggert@.hotmail.com) writes:

Quote:

Originally Posted by

The following seems to work in SQL Server 2005, but I'm getting the
error 'Incorrect syntax near xml' when I run it in SQL Server 2000.

select a.accountid , (select street, city, state, zip from account b
where a.accountid =b.accountid for xml auto, elements) as xmldata
from account a

The idea is to return 2 columns:
accountid
xmldata (address as xml)

Assuming the fields are correct, any ideas on what the problem might be?


>
The problem is simply that you try to achieve something which is not
possible in SQL 2000.
>
>
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
>
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

|||(jonathaneggert@.hotmail.com) writes:

Quote:

Originally Posted by

Well thanks for such a detailed explanation of the answer.
>
Why can't this be done in SQL Server 2000? It is a sub-query which I
have used extensively in SQL Server 2000--why the problem with FOR XML?


In SQL 2000, FOR XML can only be used in the outermost SELECT, to
produce a one-row, one-column result set. It cannot be used in subqueries,
derived tables. A good reason for this is that in SQL 2000, there is
not really any xml data type. Yet the result set returned by a FOR
XML clause is not really any of the SQL Server data types - it's XML.
It works thanks to some special hooks in the client APIs that can see
that here comes a one-row, one-column result set, which is an XML
document. There is no plumbing to permit FOR XML be composed with other
sorts of data.

This is all different in SQL 2005, where XML is a first-class citizen.

See also Books Online, the topic
XML and Internet Support ->
Retrieving and Writing XML Data ->
Retrieving XML Documents Using FOR XML ->
Guidelines for Using the FOR XML Clause

this topic lists a number of limitations with FOR XML.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx