Showing posts with label statement. Show all posts
Showing posts with label statement. Show all posts

Friday, March 23, 2012

Nested XML with XML Explicit

I am using SQL Server 2005.

I want to assign the result of a SELECT FOR XML EXPLICIT statement having an order by clause to a XML Variable such as

DECLARE @.outputXML as XML

SET @.outputXML = (
SELECT 1 as TAG, NULL as PARENT, BatchID as [Batch!1!id], NULL as [Sequence!2!id],NULL as [Step!3!id], NULL as [Device!4!DeviceName]FROM BatchDeviceMapping WHERE BatchID = 32
UNION
SELECT 2 as Tag, 1 as Parent, BatchID, SequenceID, NULL,NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 3 as Tag, 2 as Parent, BatchID, SequenceID, StepID, NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 4 as Tag, 3 as Parent, BatchID, SequenceID, StepID, Device.DeviceName FROM BatchDeviceMapping
JOIN Device Device on BatchDeviceMapping.Deviceid = device.deviceid WHERE batchID = 32 Order by 3,4,5,6 FOR XML EXPLICIT)
Its always erroring with the following information
"Msg 1086, Level 15, State 1, Line 16
The FOR XML clause is invalid in views, inline functions, derived tables, and subqueries when they contain a set operator. To work around, wrap the SELECT containing a set operator using derived table syntax and apply FOR XML on top of it."

Please note: The select query is working fine with FOR XML EXPLICIT and Order By Clause - The problem is with assigning the result of SELECT to the variable.

Any help would be appreciated.

Thanks,
Loonysan

See if this works

DECLARE @.outputXML as XML

set @.outputXML =
(
select TAG,PARENT,[Batch!1!id],[Sequence!2!id],[Step!3!id],[Device!4!DeviceName] from
(SELECT 1 as TAG, NULL as PARENT, BatchID as [Batch!1!id], NULL as [Sequence!2!id],NULL as [Step!3!id], NULL as [Device!4!DeviceName]FROM BatchDeviceMapping WHERE BatchID = 32
UNION
SELECT 2 as Tag, 1 as Parent, BatchID, SequenceID, NULL,NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 3 as Tag, 2 as Parent, BatchID, SequenceID, StepID, NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 4 as Tag, 3 as Parent, BatchID, SequenceID, StepID, Device.DeviceName FROM BatchDeviceMapping) as A
JOIN Device Device on BatchDeviceMapping.Deviceid = device.deviceid WHERE batchID = 32 Order by 3,4,5,6 FOR XML EXPLICIT)

|||

Thanks... This modified query from yr logic works..

DECLARE @.outputXML as XML

set @.outputXML =

(select TAG,PARENT,[Batch!1!id],[Sequence!2!id],[Step!3!id],[Device!4!DeviceName] from

(SELECT 1 as TAG, NULL as PARENT, BatchID as [Batch!1!id], NULL as [Sequence!2!id],NULL as [Step!3!id], NULL as [Device!4!DeviceName]FROM BatchDeviceMapping WHERE BatchID = 32
UNION
SELECT 2 as Tag, 1 as Parent, BatchID, SequenceID, NULL,NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 3 as Tag, 2 as Parent, BatchID, SequenceID, StepID, NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 4 as Tag, 3 as Parent, BatchID, SequenceID, StepID, Device.DeviceName FROM BatchDeviceMapping
JOIN Device Device on BatchDeviceMapping.Deviceid = device.deviceid where batchid = 32) as A
Order by 3,4,5,6 FOR XML EXPLICIT)
SELECT @.outputXML

Thanks,
Loonysan

|||Hi,

I'm looking for a similar solution but for SQL Server 2000. Any idea ?

(The error in SQL2000 is "Incorrect syntax near 'XML'.")

Thanks
Sylvain|||Can you give more details? The problem was not a specific one to SQL 2K5.|||

I am using SQL 2005.

I am trying to assign the result of FOX XML AUTO to a xml variable which looks something like this:

SELECT @.auditXML = (SELECT ObjectId, ObjectType, ParentId

FROM @.PermissibleChildren AS Children WHERE ObjectType = 2

UNION

SELECT [ObjectId] = MAX(ObjectId), [ObjectType] = ObjectType, [ParentId] = ParentId

FROM @.PermissibleChildren AS Children

GROUP BY ObjectType, ParentId

HAVING ObjectType = 3

FOR XML AUTO, TYPE)

It gives me this error

Msg 1086, Level 15, State 1, Procedure sf_department_openCloseFolder, Line 312

The FOR XML clause is invalid in views, inline functions, derived tables, and subqueries when they contain a set operator. To work around, wrap the SELECT containing a set operator using derived table syntax and apply FOR XML on top of it.

I have exactly the same problem as discussed in this thread. The query works fine on its own. It is only the assignment which throws this error.

Can somebody please help? I am stuck mid-way.

Thankyou,

Umaima

|||

Try this:

SELECT @.auditXML =(select objectid,ObjectType,ParentId from (SELECT ObjectId, ObjectType, ParentId

FROM @.PermissibleChildren AS Children WHERE ObjectType = 2

UNION

SELECT [ObjectId] = MAX(ObjectId), [ObjectType] = ObjectType, [ParentId] = ParentId

FROM @.PermissibleChildren AS Children

GROUP BY ObjectType, ParentId

HAVING ObjectType = 3

) as A FOR XML AUTO, TYPE)

|||

This post was extremely useful, I was trying to insert xml into a table variable where the xml was result of for XML explicit statement

Thanks

|||I had the exact same error. I solved it in the same way as you did , but my problem is that the query doesnt always run as i expect it to. Every so often Sql server throughs me back this error.
The original query worked without the error. All I did was wrap it in another select, exactly is done in the solution on this thread

6833 Parent tag ID 1 is not among the open tags. FOR XML EXPLICIT requires parent tags to be opened first. Check the ordering of the result set.

Does anybody know why that would be the case.|||Is it possible because of bad data? Since the error seems to be random, I would check the data or any other query which gets executed before this query that might change the assumptions your current query is making.|||You are getting the error because of ordering of the data.After applying the order by clause, the result set should have the parent tag ID appear before the child tag id.You can verify that by executing the query without the for xml clause.

Nested XML with XML Explicit

I am using SQL Server 2005.

I want to assign the result of a SELECT FOR XML EXPLICIT statement having an order by clause to a XML Variable such as

DECLARE @.outputXML as XML

SET @.outputXML = (
SELECT 1 as TAG, NULL as PARENT, BatchID as [Batch!1!id], NULL as [Sequence!2!id],NULL as [Step!3!id], NULL as [Device!4!DeviceName]FROM BatchDeviceMapping WHERE BatchID = 32
UNION
SELECT 2 as Tag, 1 as Parent, BatchID, SequenceID, NULL,NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 3 as Tag, 2 as Parent, BatchID, SequenceID, StepID, NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 4 as Tag, 3 as Parent, BatchID, SequenceID, StepID, Device.DeviceName FROM BatchDeviceMapping
JOIN Device Device on BatchDeviceMapping.Deviceid = device.deviceid WHERE batchID = 32 Order by 3,4,5,6 FOR XML EXPLICIT)
Its always erroring with the following information
"Msg 1086, Level 15, State 1, Line 16
The FOR XML clause is invalid in views, inline functions, derived tables, and subqueries when they contain a set operator. To work around, wrap the SELECT containing a set operator using derived table syntax and apply FOR XML on top of it."

Please note: The select query is working fine with FOR XML EXPLICIT and Order By Clause - The problem is with assigning the result of SELECT to the variable.

Any help would be appreciated.

Thanks,
Loonysan

See if this works

DECLARE @.outputXML as XML

set @.outputXML =
(
select TAG,PARENT,[Batch!1!id],[Sequence!2!id],[Step!3!id],[Device!4!DeviceName] from
(SELECT 1 as TAG, NULL as PARENT, BatchID as [Batch!1!id], NULL as [Sequence!2!id],NULL as [Step!3!id], NULL as [Device!4!DeviceName]FROM BatchDeviceMapping WHERE BatchID = 32
UNION
SELECT 2 as Tag, 1 as Parent, BatchID, SequenceID, NULL,NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 3 as Tag, 2 as Parent, BatchID, SequenceID, StepID, NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 4 as Tag, 3 as Parent, BatchID, SequenceID, StepID, Device.DeviceName FROM BatchDeviceMapping) as A
JOIN Device Device on BatchDeviceMapping.Deviceid = device.deviceid WHERE batchID = 32 Order by 3,4,5,6 FOR XML EXPLICIT)

|||

Thanks... This modified query from yr logic works..

DECLARE @.outputXML as XML

set @.outputXML =

(select TAG,PARENT,[Batch!1!id],[Sequence!2!id],[Step!3!id],[Device!4!DeviceName] from

(SELECT 1 as TAG, NULL as PARENT, BatchID as [Batch!1!id], NULL as [Sequence!2!id],NULL as [Step!3!id], NULL as [Device!4!DeviceName]FROM BatchDeviceMapping WHERE BatchID = 32
UNION
SELECT 2 as Tag, 1 as Parent, BatchID, SequenceID, NULL,NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 3 as Tag, 2 as Parent, BatchID, SequenceID, StepID, NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 4 as Tag, 3 as Parent, BatchID, SequenceID, StepID, Device.DeviceName FROM BatchDeviceMapping
JOIN Device Device on BatchDeviceMapping.Deviceid = device.deviceid where batchid = 32) as A
Order by 3,4,5,6 FOR XML EXPLICIT)
SELECT @.outputXML

Thanks,
Loonysan

|||Hi,

I'm looking for a similar solution but for SQL Server 2000. Any idea ?

(The error in SQL2000 is "Incorrect syntax near 'XML'.")

Thanks
Sylvain|||Can you give more details? The problem was not a specific one to SQL 2K5.|||

I am using SQL 2005.

I am trying to assign the result of FOX XML AUTO to a xml variable which looks something like this:

SELECT @.auditXML = (SELECT ObjectId, ObjectType, ParentId

FROM @.PermissibleChildren AS Children WHERE ObjectType = 2

UNION

SELECT [ObjectId] = MAX(ObjectId), [ObjectType] = ObjectType, [ParentId] = ParentId

FROM @.PermissibleChildren AS Children

GROUP BY ObjectType, ParentId

HAVING ObjectType = 3

FOR XML AUTO, TYPE)

It gives me this error

Msg 1086, Level 15, State 1, Procedure sf_department_openCloseFolder, Line 312

The FOR XML clause is invalid in views, inline functions, derived tables, and subqueries when they contain a set operator. To work around, wrap the SELECT containing a set operator using derived table syntax and apply FOR XML on top of it.

I have exactly the same problem as discussed in this thread. The query works fine on its own. It is only the assignment which throws this error.

Can somebody please help? I am stuck mid-way.

Thankyou,

Umaima

|||

Try this:

SELECT @.auditXML =(select objectid,ObjectType,ParentId from (SELECT ObjectId, ObjectType, ParentId

FROM @.PermissibleChildren AS Children WHERE ObjectType = 2

UNION

SELECT [ObjectId] = MAX(ObjectId), [ObjectType] = ObjectType, [ParentId] = ParentId

FROM @.PermissibleChildren AS Children

GROUP BY ObjectType, ParentId

HAVING ObjectType = 3

) as A FOR XML AUTO, TYPE)

|||

This post was extremely useful, I was trying to insert xml into a table variable where the xml was result of for XML explicit statement

Thanks

|||I had the exact same error. I solved it in the same way as you did , but my problem is that the query doesnt always run as i expect it to. Every so often Sql server throughs me back this error.
The original query worked without the error. All I did was wrap it in another select, exactly is done in the solution on this thread

6833 Parent tag ID 1 is not among the open tags. FOR XML EXPLICIT requires parent tags to be opened first. Check the ordering of the result set.

Does anybody know why that would be the case.|||Is it possible because of bad data? Since the error seems to be random, I would check the data or any other query which gets executed before this query that might change the assumptions your current query is making.|||You are getting the error because of ordering of the data.After applying the order by clause, the result set should have the parent tag ID appear before the child tag id.You can verify that by executing the query without the for xml clause.

Nested XML with XML Explicit

I am using SQL Server 2005.

I want to assign the result of a SELECT FOR XML EXPLICIT statement having an order by clause to a XML Variable such as

DECLARE @.outputXML as XML

SET @.outputXML = (
SELECT 1 as TAG, NULL as PARENT, BatchID as [Batch!1!id], NULL as [Sequence!2!id],NULL as [Step!3!id], NULL as [Device!4!DeviceName]FROM BatchDeviceMapping WHERE BatchID = 32
UNION
SELECT 2 as Tag, 1 as Parent, BatchID, SequenceID, NULL,NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 3 as Tag, 2 as Parent, BatchID, SequenceID, StepID, NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 4 as Tag, 3 as Parent, BatchID, SequenceID, StepID, Device.DeviceName FROM BatchDeviceMapping
JOIN Device Device on BatchDeviceMapping.Deviceid = device.deviceid WHERE batchID = 32 Order by 3,4,5,6 FOR XML EXPLICIT)
Its always erroring with the following information
"Msg 1086, Level 15, State 1, Line 16
The FOR XML clause is invalid in views, inline functions, derived tables, and subqueries when they contain a set operator. To work around, wrap the SELECT containing a set operator using derived table syntax and apply FOR XML on top of it."

Please note: The select query is working fine with FOR XML EXPLICIT and Order By Clause - The problem is with assigning the result of SELECT to the variable.

Any help would be appreciated.

Thanks,
Loonysan

See if this works

DECLARE @.outputXML as XML

set @.outputXML =
(
select TAG,PARENT,[Batch!1!id],[Sequence!2!id],[Step!3!id],[Device!4!DeviceName] from
(SELECT 1 as TAG, NULL as PARENT, BatchID as [Batch!1!id], NULL as [Sequence!2!id],NULL as [Step!3!id], NULL as [Device!4!DeviceName]FROM BatchDeviceMapping WHERE BatchID = 32
UNION
SELECT 2 as Tag, 1 as Parent, BatchID, SequenceID, NULL,NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 3 as Tag, 2 as Parent, BatchID, SequenceID, StepID, NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 4 as Tag, 3 as Parent, BatchID, SequenceID, StepID, Device.DeviceName FROM BatchDeviceMapping) as A
JOIN Device Device on BatchDeviceMapping.Deviceid = device.deviceid WHERE batchID = 32 Order by 3,4,5,6 FOR XML EXPLICIT)

|||

Thanks... This modified query from yr logic works..

DECLARE @.outputXML asXML

set @.outputXML =

(select TAG,PARENT,[Batch!1!id],[Sequence!2!id],[Step!3!id],[Device!4!DeviceName] from

(SELECT 1 as TAG,NULLas PARENT, BatchID as [Batch!1!id],NULLas [Sequence!2!id],NULLas [Step!3!id],NULLas [Device!4!DeviceName]FROM BatchDeviceMapping WHERE BatchID = 32
UNION
SELECT 2 as Tag, 1 as Parent, BatchID, SequenceID,NULL,NULLFROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 3 as Tag, 2 as Parent, BatchID, SequenceID, StepID,NULLFROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 4 as Tag, 3 as Parent, BatchID, SequenceID, StepID, Device.DeviceName FROM BatchDeviceMapping
JOIN Device Device on BatchDeviceMapping.Deviceid = device.deviceid where batchid = 32)as A
Orderby 3,4,5,6 FORXMLEXPLICIT)
SELECT @.outputXML

Thanks,
Loonysan

|||Hi,

I'm looking for a similar solution but for SQL Server 2000. Any idea ?

(The error in SQL2000 is "Incorrect syntax near 'XML'.")

Thanks
Sylvain
|||Can you give more details? The problem was not a specific one to SQL 2K5.|||

I am using SQL 2005.

I am trying to assign the result of FOX XML AUTO to a xml variable which looks something like this:

SELECT @.auditXML = (SELECT ObjectId, ObjectType, ParentId

FROM @.PermissibleChildren AS Children WHERE ObjectType = 2

UNION

SELECT [ObjectId] = MAX(ObjectId), [ObjectType] = ObjectType, [ParentId] = ParentId

FROM @.PermissibleChildren AS Children

GROUP BY ObjectType, ParentId

HAVING ObjectType = 3

FOR XML AUTO, TYPE)

It gives me this error

Msg 1086, Level 15, State 1, Procedure sf_department_openCloseFolder, Line 312

The FOR XML clause is invalid in views, inline functions, derived tables, and subqueries when they contain a set operator. To work around, wrap the SELECT containing a set operator using derived table syntax and apply FOR XML on top of it.

I have exactly the same problem as discussed in this thread. The query works fine on its own. It is only the assignment which throws this error.

Can somebody please help? I am stuck mid-way.

Thankyou,

Umaima

|||

Try this:

SELECT @.auditXML =(select objectid,ObjectType,ParentId from(SELECT ObjectId, ObjectType, ParentId

FROM @.PermissibleChildren AS Children WHERE ObjectType = 2

UNION

SELECT [ObjectId] =MAX(ObjectId), [ObjectType] = ObjectType, [ParentId] = ParentId

FROM @.PermissibleChildren AS Children

GROUPBY ObjectType, ParentId

HAVING ObjectType = 3

)as A FORXMLAUTO,TYPE)

|||

This post was extremely useful, I was trying to insert xml into a table variable where the xml was result of for XML explicit statement

Thanks

|||I had the exact same error. I solved it in the same way as you did , but my problem is that the query doesnt always run as i expect it to. Every so often Sql server throughs me back this error.
The original query worked without the error. All I did was wrap it in another select, exactly is done in the solution on this thread

6833 Parent tag ID 1 is not among the open tags. FOR XML EXPLICIT requires parent tags to be opened first. Check the ordering of the result set.

Does anybody know why that would be the case.

|||Is it possible because of bad data? Since the error seems to be random, I would check the data or any other query which gets executed before this query that might change the assumptions your current query is making.|||You are getting the error because of ordering of the data.After applying the order by clause, the result set should have the parent tag ID appear before the child tag id.You can verify that by executing the query without the for xml clause.

Nested XML with XML Explicit

I am using SQL Server 2005.

I want to assign the result of a SELECT FOR XML EXPLICIT statement having an order by clause to a XML Variable such as

DECLARE @.outputXML as XML

SET @.outputXML = (
SELECT 1 as TAG, NULL as PARENT, BatchID as [Batch!1!id], NULL as [Sequence!2!id],NULL as [Step!3!id], NULL as [Device!4!DeviceName]FROM BatchDeviceMapping WHERE BatchID = 32
UNION
SELECT 2 as Tag, 1 as Parent, BatchID, SequenceID, NULL,NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 3 as Tag, 2 as Parent, BatchID, SequenceID, StepID, NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 4 as Tag, 3 as Parent, BatchID, SequenceID, StepID, Device.DeviceName FROM BatchDeviceMapping
JOIN Device Device on BatchDeviceMapping.Deviceid = device.deviceid WHERE batchID = 32 Order by 3,4,5,6 FOR XML EXPLICIT)
Its always erroring with the following information
"Msg 1086, Level 15, State 1, Line 16
The FOR XML clause is invalid in views, inline functions, derived tables, and subqueries when they contain a set operator. To work around, wrap the SELECT containing a set operator using derived table syntax and apply FOR XML on top of it."

Please note: The select query is working fine with FOR XML EXPLICIT and Order By Clause - The problem is with assigning the result of SELECT to the variable.

Any help would be appreciated.

Thanks,
Loonysan

See if this works

DECLARE @.outputXML as XML

set @.outputXML =
(
select TAG,PARENT,[Batch!1!id],[Sequence!2!id],[Step!3!id],[Device!4!DeviceName] from
(SELECT 1 as TAG, NULL as PARENT, BatchID as [Batch!1!id], NULL as [Sequence!2!id],NULL as [Step!3!id], NULL as [Device!4!DeviceName]FROM BatchDeviceMapping WHERE BatchID = 32
UNION
SELECT 2 as Tag, 1 as Parent, BatchID, SequenceID, NULL,NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 3 as Tag, 2 as Parent, BatchID, SequenceID, StepID, NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 4 as Tag, 3 as Parent, BatchID, SequenceID, StepID, Device.DeviceName FROM BatchDeviceMapping) as A
JOIN Device Device on BatchDeviceMapping.Deviceid = device.deviceid WHERE batchID = 32 Order by 3,4,5,6 FOR XML EXPLICIT)

|||

Thanks... This modified query from yr logic works..

DECLARE @.outputXML as XML

set @.outputXML =

(select TAG,PARENT,[Batch!1!id],[Sequence!2!id],[Step!3!id],[Device!4!DeviceName] from

(SELECT 1 as TAG, NULL as PARENT, BatchID as [Batch!1!id], NULL as [Sequence!2!id],NULL as [Step!3!id], NULL as [Device!4!DeviceName]FROM BatchDeviceMapping WHERE BatchID = 32
UNION
SELECT 2 as Tag, 1 as Parent, BatchID, SequenceID, NULL,NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 3 as Tag, 2 as Parent, BatchID, SequenceID, StepID, NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 4 as Tag, 3 as Parent, BatchID, SequenceID, StepID, Device.DeviceName FROM BatchDeviceMapping
JOIN Device Device on BatchDeviceMapping.Deviceid = device.deviceid where batchid = 32) as A
Order by 3,4,5,6 FOR XML EXPLICIT)
SELECT @.outputXML

Thanks,
Loonysan

|||Hi,

I'm looking for a similar solution but for SQL Server 2000. Any idea ?

(The error in SQL2000 is "Incorrect syntax near 'XML'.")

Thanks
Sylvain
|||Can you give more details? The problem was not a specific one to SQL 2K5.|||

I am using SQL 2005.

I am trying to assign the result of FOX XML AUTO to a xml variable which looks something like this:

SELECT @.auditXML = (SELECT ObjectId, ObjectType, ParentId

FROM @.PermissibleChildren AS Children WHERE ObjectType = 2

UNION

SELECT [ObjectId] = MAX(ObjectId), [ObjectType] = ObjectType, [ParentId] = ParentId

FROM @.PermissibleChildren AS Children

GROUP BY ObjectType, ParentId

HAVING ObjectType = 3

FOR XML AUTO, TYPE)

It gives me this error

Msg 1086, Level 15, State 1, Procedure sf_department_openCloseFolder, Line 312

The FOR XML clause is invalid in views, inline functions, derived tables, and subqueries when they contain a set operator. To work around, wrap the SELECT containing a set operator using derived table syntax and apply FOR XML on top of it.

I have exactly the same problem as discussed in this thread. The query works fine on its own. It is only the assignment which throws this error.

Can somebody please help? I am stuck mid-way.

Thankyou,

Umaima

|||

Try this:

SELECT @.auditXML =(select objectid,ObjectType,ParentId from (SELECT ObjectId, ObjectType, ParentId

FROM @.PermissibleChildren AS Children WHERE ObjectType = 2

UNION

SELECT [ObjectId] = MAX(ObjectId), [ObjectType] = ObjectType, [ParentId] = ParentId

FROM @.PermissibleChildren AS Children

GROUP BY ObjectType, ParentId

HAVING ObjectType = 3

) as A FOR XML AUTO, TYPE)

|||

This post was extremely useful, I was trying to insert xml into a table variable where the xml was result of for XML explicit statement

Thanks

|||I had the exact same error. I solved it in the same way as you did , but my problem is that the query doesnt always run as i expect it to. Every so often Sql server throughs me back this error.
The original query worked without the error. All I did was wrap it in another select, exactly is done in the solution on this thread

6833 Parent tag ID 1 is not among the open tags. FOR XML EXPLICIT requires parent tags to be opened first. Check the ordering of the result set.

Does anybody know why that would be the case.

|||Is it possible because of bad data? Since the error seems to be random, I would check the data or any other query which gets executed before this query that might change the assumptions your current query is making.|||You are getting the error because of ordering of the data.After applying the order by clause, the result set should have the parent tag ID appear before the child tag id.You can verify that by executing the query without the for xml clause.

Nested XML with XML Explicit

I am using SQL Server 2005.

I want to assign the result of a SELECT FOR XML EXPLICIT statement having an order by clause to a XML Variable such as

DECLARE @.outputXML as XML

SET @.outputXML = (
SELECT 1 as TAG, NULL as PARENT, BatchID as [Batch!1!id], NULL as [Sequence!2!id],NULL as [Step!3!id], NULL as [Device!4!DeviceName]FROM BatchDeviceMapping WHERE BatchID = 32
UNION
SELECT 2 as Tag, 1 as Parent, BatchID, SequenceID, NULL,NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 3 as Tag, 2 as Parent, BatchID, SequenceID, StepID, NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 4 as Tag, 3 as Parent, BatchID, SequenceID, StepID, Device.DeviceName FROM BatchDeviceMapping
JOIN Device Device on BatchDeviceMapping.Deviceid = device.deviceid WHERE batchID = 32 Order by 3,4,5,6 FOR XML EXPLICIT)
Its always erroring with the following information
"Msg 1086, Level 15, State 1, Line 16
The FOR XML clause is invalid in views, inline functions, derived tables, and subqueries when they contain a set operator. To work around, wrap the SELECT containing a set operator using derived table syntax and apply FOR XML on top of it."

Please note: The select query is working fine with FOR XML EXPLICIT and Order By Clause - The problem is with assigning the result of SELECT to the variable.

Any help would be appreciated.

Thanks,
Loonysan

See if this works

DECLARE @.outputXML as XML

set @.outputXML =
(
select TAG,PARENT,[Batch!1!id],[Sequence!2!id],[Step!3!id],[Device!4!DeviceName] from
(SELECT 1 as TAG, NULL as PARENT, BatchID as [Batch!1!id], NULL as [Sequence!2!id],NULL as [Step!3!id], NULL as [Device!4!DeviceName]FROM BatchDeviceMapping WHERE BatchID = 32
UNION
SELECT 2 as Tag, 1 as Parent, BatchID, SequenceID, NULL,NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 3 as Tag, 2 as Parent, BatchID, SequenceID, StepID, NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 4 as Tag, 3 as Parent, BatchID, SequenceID, StepID, Device.DeviceName FROM BatchDeviceMapping) as A
JOIN Device Device on BatchDeviceMapping.Deviceid = device.deviceid WHERE batchID = 32 Order by 3,4,5,6 FOR XML EXPLICIT)

|||

Thanks... This modified query from yr logic works..

DECLARE @.outputXML as XML

set @.outputXML =

(select TAG,PARENT,[Batch!1!id],[Sequence!2!id],[Step!3!id],[Device!4!DeviceName] from

(SELECT 1 as TAG, NULL as PARENT, BatchID as [Batch!1!id], NULL as [Sequence!2!id],NULL as [Step!3!id], NULL as [Device!4!DeviceName]FROM BatchDeviceMapping WHERE BatchID = 32
UNION
SELECT 2 as Tag, 1 as Parent, BatchID, SequenceID, NULL,NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 3 as Tag, 2 as Parent, BatchID, SequenceID, StepID, NULL FROM BatchDeviceMapping WHERE batchID = 32
UNION
SELECT 4 as Tag, 3 as Parent, BatchID, SequenceID, StepID, Device.DeviceName FROM BatchDeviceMapping
JOIN Device Device on BatchDeviceMapping.Deviceid = device.deviceid where batchid = 32) as A
Order by 3,4,5,6 FOR XML EXPLICIT)
SELECT @.outputXML

Thanks,
Loonysan

|||Hi,

I'm looking for a similar solution but for SQL Server 2000. Any idea ?

(The error in SQL2000 is "Incorrect syntax near 'XML'.")

Thanks
Sylvain
|||Can you give more details? The problem was not a specific one to SQL 2K5.|||

I am using SQL 2005.

I am trying to assign the result of FOX XML AUTO to a xml variable which looks something like this:

SELECT @.auditXML = (SELECT ObjectId, ObjectType, ParentId

FROM @.PermissibleChildren AS Children WHERE ObjectType = 2

UNION

SELECT [ObjectId] = MAX(ObjectId), [ObjectType] = ObjectType, [ParentId] = ParentId

FROM @.PermissibleChildren AS Children

GROUP BY ObjectType, ParentId

HAVING ObjectType = 3

FOR XML AUTO, TYPE)

It gives me this error

Msg 1086, Level 15, State 1, Procedure sf_department_openCloseFolder, Line 312

The FOR XML clause is invalid in views, inline functions, derived tables, and subqueries when they contain a set operator. To work around, wrap the SELECT containing a set operator using derived table syntax and apply FOR XML on top of it.

I have exactly the same problem as discussed in this thread. The query works fine on its own. It is only the assignment which throws this error.

Can somebody please help? I am stuck mid-way.

Thankyou,

Umaima

|||

Try this:

SELECT @.auditXML =(select objectid,ObjectType,ParentId from (SELECT ObjectId, ObjectType, ParentId

FROM @.PermissibleChildren AS Children WHERE ObjectType = 2

UNION

SELECT [ObjectId] = MAX(ObjectId), [ObjectType] = ObjectType, [ParentId] = ParentId

FROM @.PermissibleChildren AS Children

GROUP BY ObjectType, ParentId

HAVING ObjectType = 3

) as A FOR XML AUTO, TYPE)

|||

This post was extremely useful, I was trying to insert xml into a table variable where the xml was result of for XML explicit statement

Thanks

|||I had the exact same error. I solved it in the same way as you did , but my problem is that the query doesnt always run as i expect it to. Every so often Sql server throughs me back this error.
The original query worked without the error. All I did was wrap it in another select, exactly is done in the solution on this thread

6833 Parent tag ID 1 is not among the open tags. FOR XML EXPLICIT requires parent tags to be opened first. Check the ordering of the result set.

Does anybody know why that would be the case.

|||Is it possible because of bad data? Since the error seems to be random, I would check the data or any other query which gets executed before this query that might change the assumptions your current query is making.|||You are getting the error because of ordering of the data.After applying the order by clause, the result set should have the parent tag ID appear before the child tag id.You can verify that by executing the query without the for xml clause.sql

Nested transactions question.

Hope I am posting in the right forum. If I understand correctly, a ROLLBACK TRAN statement rolls all transactions (if they are nested) back to the original BEGIN TRAN.

I have a situation when an SP uses a transaction, performs a series of operations inside that transaction, including a call to a different SP, which uses a distributed transaction. If the transaction inside the child SP fails and needs to be rolled back, I get a warning message saying that the tran count on the way out is less than that on the way in. No problem, since it's not fatal. But the problem manifests when I attempt to use the SQL Agent to schedule a job to run the parent SP. It fails on that warning message, interpreting it as an error.

I was thinking of disabling the distributed transaction inside the child SP, and just have the transaction in the parent SP, which, again if I understand correctly, should be escalated to a distributed transaction once the child SP is called. The child SP will raise an error (if it's a real error) and then the trnasaction in the parent SP will handle the rollback of everything.

The reason for this elaborate setup is that I need to cycle through a cursor (yes, I know, sloppy, can't see an alternative) in the parent SP, and each iteration begins and commits (or rolls back) a transaction.

Wil this work? Can anyone suggest a better way?

will this help.

select name
into #tb
from master..systypes
go
select * from #tb
go
declare cc cursor forward_only
for select name from #tb

declare @.name sysname
open cc
fetch next from cc into @.name

while @.@.fetch_status=0
begin
begin tran
delete #tb
where name=@.name and name!='sysname'
if @.@.error=0
commit tran
else
rollback tran

fetch next from cc into @.name
end
close cc
deallocate cc
go
select * from #tb
select @.@.trancount
go

if object_id('tempdb..#tb') is not null
drop table #tb
go

|||Hmmm.... Not sure I understand. This is more or less the code I have. Except for where you have "DELETE #tb WHERE..." I have "EXEC spMyStoredProc @.myInputParam". and inside "spMyStoredProc" there is a distributed tran. So the @.@.TRANCOUNT at the beginning of spMyStoredProc is equal to 1. But inside the SP, let's say the transaction fails for whatever reason, and a ROLLBACK is called. The @.@.TRANCOUNT is set to 0 by the ROLLBACK statement. And now @.@.TRANCOUNT at the end of the SP is less than it was at the beginning. That generates a warning message. But apparently the SQL Agent that handles the Job execution treats it as an error. Or the error that caused the ROLLBACK was raised - I am not sure. In any case - Job ends. But I need it to continue. If I just run the code from QueryAnalyzer - it's ok. It generates warnings, but runs through all the cycles. How can I avoid being bounced out of a SQL Job?|||

(Hope I am posting in the right forum. If I understand correctly, a ROLLBACK TRAN statement rolls all transactions (if they are nested) back to the original BEGIN TRAN.)

That is actually not correct if you use Transaction Save Points which you can roll back as needed after service pack 3a of SQL Server 2000. Now to your question add Transaction save points to any Transaction you don't want rolled back with the error code. Run some tests, transaction is a unit of work but the vendors like Microsoft added Save Points which enable nested Transaction without a roll back to one, with Save Points if you fail at number 100 you will have 99 completed. Run a search for Save Points in the BOL. Hope this helps.

|||

Thanks for pointing out the SavePoints. I did research tehm, but I am not sure if this applies here. I guess I am not explaining the issue clearly enough. I DO want the transactions, both of them, rolled back if an error is encountered in either. However, I have a scenario where the parent transaction is in a cursor (just like that code sample above shows). Each cursor iteration begins and ends a transaction. Each of those transactions calls an SP with another (child) transaction. If anything breaks, I want the transactions to roll back, then I want to go on to the next cursor iteration. If I execute the code in QueryAnalyzer - it works fine. If I schedule the execution via an SQL Job - the Job abends on the first error, rolls back the transaction but does NOT go on to the next cursor iteration. My guess is, this is because the warning that is raised by the child SP (standard non-fatal warning that tran count at the beginning of the SP does not match that at the end) is treated as a fatal error by the SQL Agent, and it terminates the Job.

I could be wrong, and it could be the actuall error that caused the transaction rollback in the first place is being raised, and the Agent may be reacting to that. Whatever the case - My Job stops the cursor execution and exits with an error. Which is something I would like to avoid.

|||

If you can run it and the Agent is not running it, that maybe permissions related when you run it is it running under your admin level permissions but when the Agent runs it, it is running under the Agent's permissions so it will not continue after an error in transactions. You can enable xp_cmdshell in the Surface area configuration tool then create a proxy account for the Agent with your admin level permissions. Run a search for Agent proxy account in the BOL, xp_cmdshell is finally documented but disabled by default so you need to enable it in the Surface area configuration tool. If the permission does not solve the problem then you need to separate your transactions into blocks and connect them with sp_executesql or exec statements. Hope this helps.

|||Thanks. My agent is running with admin permissions already, though :-( Final question - my child SP is written in such a way that I can pass it a flag that governs whether or not I want to use transactions (did that for testing). If I disable the child transaction (its a distributed tran), will a rollback on the parent also roll back the changes made by the sub-called SP? I think that the parent transaction will be automatically escalated to distriburted tran in this case, but I am not sure. I can make it into a distributed transaction manually, if needs be. From what I can see - this would be my only option unless I want to duplicate a lot of code.|||

(will a rollback on the parent also roll back the changes made by the sub-called SP?)

No if each is separated by save points and if you are not using MSDTC maybe you should look into it.

|||

They are not separated by save points.

Main SP code:

Code Snippet

OPEN curCustomersToCancel
FETCH NEXT FROM curCustomersToCancel INTO @.CustID
WHILE @.@.FETCH_STATUS = 0
BEGIN
BEGIN DISTRIBUTED TRAN

EXEC @.ReturnCde = spCancelServices @.CustID
If @.ReturnCde <> 0
Begin
IF(@.@.TRANCOUNT > 0) ROLLBACK TRAN

Select @.SpErrDesc = @.retmsg
PRINT '******* @.SpErrDesc = ' + @.SpErrDesc
BREAK
End

Else

Begin

IF(@.@.TRANCOUNT > 0) COMMIT TRAN

End

FETCH NEXT FROM curCustomersToCancel INTO @.CustID

END
CLOSE curCustomersToCancel
DEALLOCATE curCustomersToCancel

The code in spCancelServices has no transactions - it's just a series of SQL statements. Will this properly roll back all modifications made inside spCancelServices in case of an error?

|||

In the link below download the file SQLServer2005_US_ALL on the left side and in there check samples for chapter 13 and 14 in the notepad files and the PDF note that one trigger in chapter 13 can do what you want. And you did not include @.@.Error in your code, if I remember correctly Fetch is an implicit transaction per ANSI SQL. The author Dusan Petkovic got bad book title but he covered SQL Server transaction better than most writers. Hope this helps.


http://www.mhprofessional.com/product.php?cat=112&isbn=0072260939

Wednesday, March 21, 2012

nested Sum and DistinctCount error. Help!

Hi I'm really a newb at CR, (started this monday), and I wanted to do a statement like this:

Sum(DistinctCount({db_column3}, {db_column2}), {db_column1})

where the db_column1 can have many db_column2, and db_column2 can have many (repetitious) db_column3.

I'm assuming this wont work because one can't have a sum of a count, but what can I write that is to this effect? thanks a lot in advance!

Tom

Edit, i just tried doing Sum(DistinctCount(blah.. on something trivial, and it worked. So perhaps there are some constraints on the Cond in Sum(blah, Cond) that I don't know. Any enlightenment is much appreciated!>>i just tried doing Sum(DistinctCount(blah.. on something trivial, and it worked.

Then where are you struggling?

Nested SQL(Nested SQL(Nested SQL(Nested SQL)))

Can you give a whole SQL statement an alias so you can use it later?

Eg.

SELECT * FROM Employees WHERE age < 19
-- Could I call the above statement something like 'statement1' to use below as shown

SELECT * FROM Employees WHERE age < 25 AND NOT IN (statement1)

Soin effect I get a nested statement.
The reason I am asking about aliases is because this would need to be repeated for, E.g. age < 30 Then age < 35 and so on and so forth.

So basically, I just want to alias a qhole SQL statement

Any help would be greatly appreciated - Georgethe concept you are thinking of is called a view

so, the answer is yes, you can|||Could you elaborate slightly please?
Could you perhaps include an example of hwo to reference/alias/view an sql statement.

Thanks mate|||Something like this?CREATE VIEW stat_1 AS
SELECT * FROM employees WHERE age < 19;

CREATE VIEW stat_2 AS
SELECT * FROM employees
WHERE age < 25
AND employee_id NOT IN (SELECT employee_id FROM stat_1);|||I'm using a program called QUERY ANALYZER in which I am the following (and just to confuse I am now trying qualifications..

CREATE VIEW stat_1 AS
SELECT e.employee_number
FROM pwa_master.employee e, pwa_master.trgqual t
WHERE t.qualification_level = 'ALEV'

CREATE VIEW stat_2 AS
SELECT e.employee_number, t.qualification_level
FROM pwa_master.employee e, pwa_master.trgqual t
WHERE t.qualification_level = 'GCSE'
AND e.employee_number NOT IN (SELECT e.employee_number FROM stat_1)

From which I get the following message:

Server: Msg 2714, Level 16, State 5, Procedure stat_1, Line 2
There is already an object named 'stat_1' in the database

I don't know what I have done, but it doesn't look good.

Normally in this program if I do a select it only displays the results, which is all I want to do, not create anything in the database! :S :o :confused: :shocked:|||if you run CREATE VIEW stat_1 more than once, guess what happens on the second attempt?

a view is simple a query definition -- it's exactly what you want

yes, the query definition gets stored in your database

if you don't want to store the view definition in your database, you cannot use a view|||I dont want to store anything in the database, just use SQL to extract the data I need.

So are there any other methods I can use instead of a view?

P.S. When a view is created, where in the database is it stored?|||I dont want to store anything in the database, just use SQL to extract the data I need.you can always do that

So are there any other methods I can use instead of a view?depends on what you are really trying to do, which isn't really clear

P.S. When a view is created, where in the database is it stored?in the system tables|||Ok, I'll try and clarify.

Employees table is linked to a table called Training and Qualifications.
I have been asked to produce an SQL statement that selects an employees' highest qualification. Unfortunately I cannot do this with things such as child functions or even entry date as this will be innacurate.

Unfortunately there is no ranking available in the database to signify which qualification is highest E.g. GCSE, ALevels, OLevels, Masters etc etc.

So I thought that if I could say, have one SQL statement for each and gave them each an alias I could do the following:

SELECT employee_number
FROM training_and_qualifications
WHERE Qualification_Level = 'GCSE'
AND Qualification_Level NOT IN [SQL Statement 2]

the previous one would be of a similar format again, but GCSE could be replaced with 'ALEV' and used NOT IN [SQL Statement 3].

Is that any better?
If not - I'm sorry :o|||you should have posted your original requirements first, instead of asking how to accomplish something really complicated

"I have been asked to produce an SQL statement that selects an employees' highest qualification"

please give information about the ranking of these qualifications|||That's the problem, there is no ranking.

I would have to do it logically which is why I was building this sql statement.
I would take the highest qualification (Masters I think) and that would be my very first SQL statement.

Then I would perform another one for, say, ALevels and use "NOT IN MastersSQLStatement"

Followed by GCSE (?) and use "NOT IN MastersSQLStatement OR NOT IN ALevelsSQLStatement"

Sorry for complicating the issue.|||if there is no ranking, then you could never pick the highest one, could you

so of course there's a ranking

you said yourself that Masters is the highest, but i bet Doctors is even higher, and Bachelors is next highest after Masters, and so on

if an employee has several qualifications, how are they stored?

you need to give information about your table structure|||There is no ranking stored in the database, I am producing the order myself.
I wouldn't have a problem if in the database each qualification has a rank number, but I am unable to amend the tables to do such a thing.

training_and_qualifications table is linked to the employees table by the employees unique_identifier.

In the training_and_qualifications table each row has its own unique_identifier.

therefore one employee can have many qualifications, linked by the employee unique ID|||There is no ranking stored in the database, I am producing the order myself.i do realize there is no ranking stored in the database, however, if you don't share this information with me, i cannot help you

what are the rankings?|||This discussion reminds me of something that happened ages ago when I was a teenager and worked in a service station. One morning I showed up to open up, and found a car parked on the driveway, no keys, with a note on the windshield that said "something is wrong".

Looking at the car, my first thought was "Obviously" which was quickly followed by "What is this thing doing squarely in the middle of my driveway?" although the phrasing was a bit different. ;)

I'm sure that we can help you. I'm comfortable that your database design needs some small changes, specifically you need a table that includes all of the qualifications you use with a ranking for each of them.

As we know that this uses Microsoft SQL Server, and is almost certainly using SQL 2000 instead of SQL 2005, that helps us too. In order to get more relevant comments, I'm going to move the whole thread to the Microsoft SQL Server forum where more people will find it and contribute to helping solve your problem(s).

At the top of every page in the Microsoft SQL forum is a FAQ. In the FAQ is a post describing how to get fast and correct answers to your questions. Please read that post, the ideas there will help you get a faster and less frustrating answer for your question!

-PatP|||for the sake of a quick response (there are 77 different qualifications in the code table). Here is a condensed list or 5 in order.

Highest

MAST (Masters)
ALEV (A Level)
ASLEV (AS Level)
GCSE (GCSE)
CG (City and Guilds)

Lowest

Hope it helps|||Ok, so create a list of the qualifications (if you show your table layouts, I can provide code that will help you with this), and then assign each one a number. I'd start numbering at 100000 and bump the number by 1000 for each higher qualification. That gives you lots of room in case you need to rearrange things later.

Once you create this table, then things are relatively easy, but we'll take things one step at a time for now.

-PatP|||Thanks Pat.

The database contains a table called "Qualifications_Code_List" which has 77 rows, each one has a unique "Qualification_Code" and "Description".

I know the simplest way would be to add a third column in which I could assign a numeric value for rank. BUT I am supposed to be doing this without changing the database, hence this workaround.

tomake a change to the tables would require exclusive access, i.e. booting everyone off the system. At the end of the month we are taking the system offline for 6hours, so if all else fails I can impliment this then along with lots the other changes.

I'm just being nagged to give these people an answer sooner than that :p

Oh, and I realise my original post was.. well.. rubbish, so I apologise.
I will read up on the FAQ and hopefull next time I will be better.

thanks for all the replies everyone :beer: cheers!|||Ok, so create a list of the qualifications (if you show your table layouts, I can provide code that will help you with this), and then assign each one a number. I'd start numbering at 100000 and bump the number by 1000 for each higher qualification. That gives you lots of room in case you need to rearrange things later.

Once you create this table, then things are relatively easy, but we'll take things one step at a time for now.

-PatP

Very good idea using 1000's instead, I wouldn't have thought of that, thanks!|||I'm just being nagged to give these people an answer sooner than that :ptell them you cannot do it until they provide you with a list in sorted order

how the heck are you supposed to run a query if you're not sure about the ranking values?

there's no way i would guess at how to find the "highest" value from amongst 77 different values

and i would have no problem telling the users that they aren't going to get what they want until they are more forthcoming|||Check out ALTER TABLE, it requires the use of SQL syntax instead of the GUI, but it allows you to add a column in real time without your users being aware that anything happened.

The next time they do a SELECT * FROM yourTable there will suddenly be a new column. Note that you should try this in a dev/test environment before you rip into production, but ALTER TABLE will have no adverse affect on online users (other than adding the column to the table).

-PatP|||IF I eventually get this with rankings in the database table, I just sort by rank or whatever...

IF I cannot amend the table but I still have an ordered list, i.e. I know the order, can I use sql to create it?

I know it will be a huge pain in the a** but still :p

Sorry eveyone :o|||SELECT employees.unique_identifier
, case when exists
( select 1
from training_and_qualifications
where employee_unique_identifier
= employees.unique_identifier
and Qualification_Level = 'MAST' )
then 'Masters'
when exists
( select 1
from training_and_qualifications
where employee_unique_identifier
= employees.unique_identifier
and Qualification_Level = 'ALEV' )
then 'A Level'
when exists
( select 1
from training_and_qualifications
where employee_unique_identifier
= employees.unique_identifier
and Qualification_Level = 'ASLEV' )
then 'AS Level'
when exists
( select 1
from training_and_qualifications
where employee_unique_identifier
= employees.unique_identifier
and Qualification_Level = 'GCSE' )
then 'GCSE'
when exists
( select 1
from training_and_qualifications
where employee_unique_identifier
= employees.unique_identifier
and Qualification_Level = 'CG' )
then 'City and Guilds'
else '*none*'
end as highest_qualification
FROM employeesthe reason this works is because a CASE expression is evaluated linearly, so the first WHEN clause that evaluates true will determine the result, which in this instance is a column called "highest_qualification"

simply create as many WHEN clauses as you have qualifications

simple, yes?|||Check out ALTER TABLE, it requires the use of SQL syntax instead of the GUI, but it allows you to add a column in real time without your users being aware that anything happened.

The next time they do a SELECT * FROM yourTable there will suddenly be a new column. Note that you should try this in a dev/test environment before you rip into production, but ALTER TABLE will have no adverse affect on online users (other than adding the column to the table).

-PatP

Sadly I have tried this in the past in our test environment, and through the query analyzer you can populate the row, but it remains unrecognised in the system (complete pain in the a**). This means when I create a query within the system for the users.. use.. I cannot select that row because it just simply cannot be seen!

We use a system called Empower which is an ex microsoft product.|||There are ten thousand solutions for almost any problem. About nine thousand, nine hundred and ninety four of them are impractical.

You could always take the "outsourcing approach" and ship all of the data overseas, have someone read your data and produce a sorted list, then you can describe the selection criteria (for order of qualifications) and tell them to discard everything except for the highest qualification. You can probably do this in less than a year, and it will probably take a few days for each run of the list, but it will be reasonably priced when it does work!

-PatP|||You can't just edit a result set in Query Analyzer. That tool is really for developers, not for users, so there is no "push" technology in it... Any changes you make are local to your own machine, they are never returned to the database.

If you use another tool to access the table such as Microsoft Access, then you can make the kind of changes you are envisioning. You can also write SQL statements to UPDATE the database, which is a bit of a pain, but is often my tool of preference.

-PatP|||SELECT employees.unique_identifier
, case when exists
( select 1
from training_and_qualifications
where employee_unique_identifier
= employees.unique_identifier
and Qualification_Level = 'MAST' )
then 'Masters'
when exists
( select 1
from training_and_qualifications
where employee_unique_identifier
= employees.unique_identifier
and Qualification_Level = 'ALEV' )
then 'A Level'
when exists
( select 1
from training_and_qualifications
where employee_unique_identifier
= employees.unique_identifier
and Qualification_Level = 'ASLEV' )
then 'AS Level'
when exists
( select 1
from training_and_qualifications
where employee_unique_identifier
= employees.unique_identifier
and Qualification_Level = 'GCSE' )
then 'GCSE'
when exists
( select 1
from training_and_qualifications
where employee_unique_identifier
= employees.unique_identifier
and Qualification_Level = 'CG' )
then 'City and Guilds'
else '*none*'
end as highest_qualification
FROM employeesthe reason this works is because a CASE expression is evaluated linearly, so the first WHEN clause that evaluates true will determine the result, which in this instance is a column called "highest_qualification"

simply create as many WHEN clauses as you have qualifications

simple, yes?

THIS WORKS!
Now to implemment the other 72 select statements :P
Atleast I can now tell them that it, atleast in theory, is possible without editing the database.

I love you ;)

Thank you everyone for all your help (and for putting up with me).|||You can't just edit a result set in Query Analyzer. That tool is really for developers, not for users, so there is no "push" technology in it... Any changes you make are local to your own machine, they are never returned to the database.

If you use another tool to access the table such as Microsoft Access, then you can make the kind of changes you are envisioning. You can also write SQL statements to UPDATE the database, which is a bit of a pain, but is often my tool of preference.

-PatP

They only really want a spreadsheet at the end of it all, so I will just run it and paste it int a spreadheet and voila! (ish) :p

cheers Pat|||Actually once you get the SQL worked out, Excel 2000 includes a nifty feature under Data | Get External Data | Database Query that makes this process a lot easier (and is repeatable too).

-PatP|||Can you give a whole SQL statement an alias so you can use it later?
This is not necessarily a VIEW: views are stored in the database, while you might just want to use the "alias" for the current query only.

In that case a common table expression is more appropriate.
CTEs precede an SQL Select statemant in a WITH subclause.

Example:WITH stat_1 AS
( SELECT e.employee_number AS n1
FROM pwa_master.employee AS e, pwa_master.trgqual AS t
WHERE t.qualification_level = 'ALEV'
),
stat_2 AS
( SELECT e.employee_number AS n2
FROM pwa_master.employee AS e, pwa_master.trgqual AS t
WHERE t.qualification_level = 'GCSE'
)
SELECT stat_1.unique_identifier,
COALESCE(n1, n2)
FROM stat_1 FULL OUTER JOIN stat_2 ON n1 = n2|||if you don't have any other method, you can always rank your items this way:

select * from yourtable order by newid()

;)

EDIT: tell your boss that you are using Bayesian classifiers to determine the ranking.|||This is not necessarily a VIEW: views are stored in the database, while you might just want to use the "alias" for the current query only.

In that case a common table expression is more appropriate.
CTEs precede an SQL Select statemant in a WITH subclause.

Example:WITH stat_1 AS
( SELECT e.employee_number AS n1
FROM pwa_master.employee AS e, pwa_master.trgqual AS t
WHERE t.qualification_level = 'ALEV'
),
stat_2 AS
( SELECT e.employee_number AS n2
FROM pwa_master.employee AS e, pwa_master.trgqual AS t
WHERE t.qualification_level = 'GCSE'
)
SELECT stat_1.unique_identifier,
COALESCE(n1, n2)
FROM stat_1 FULL OUTER JOIN stat_2 ON n1 = n2

I ran this and got the following:

Server: Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'WITH'.
Server: Msg 170, Level 15, State 1, Line 6
Line 6: Incorrect syntax near ','.

I understand what the code is supposed to do - but I don't know what the syntax should be!|||you have to wait until SQL Server 2005 to use CTEs|||I have SQL Server 2005 installed on this machine - but I have nno idea how to use it. :p

But thanks for the reply mate - it's all realllllly useful!
Even if it's not something I can use now this is all great to learn!|||There one other thing you can do, provided that you know the order of the ranking.
--Create a temp-table:
CREATE TABLE #tmprank (rank INT IDENTITY, desc VARCHAR(10))

--Fill the temp-table with the ranking in the right order:
INSERT #tmprank (desc) VALUES ('MAST')
INSERT #tmprank (desc) VALUES ('ALEV')
INSERT #tmprank (desc) VALUES ('ASLEV')
INSERT #tmprank (desc) VALUES ('GCSE')
INSERT #tmprank (desc) VALUES ('CG')

--Join your query to this temp-table and order by rank:
SELECT employees.unique_identifier, t.rank, t.desc
FROM employees e
INNER JOIN #tmprank t ON t.desc = e.Qualification_Level
ORDER BY t.rank

--Drop the temp-table (closing the session will also do this)
DROP TABLE #tmprank
This is a non-intrusive way that leaves no traces (does not alter the structure of your db).

Monday, March 19, 2012

nested loops join

Hi,
I have a select statement that gets data from only one table.
When I write OPTION(LOOP JOIN) after this query and run it, the
execution time is 2-3 times faster than without OPTION(LOOP JOIN).
If I use OPTION(FAST 1) the execution time is as fast as with OPTION(LOOP
JOIN)
Does anyone know why its faster with nested loops join even though I don't
join any tables?
Thanks!
//MalinDid you look at the actual execution plan to see what it is doing in both
cases?
Andrew J. Kelly SQL MVP
"Malin Davidsson" <malin.davidsson(at)aus.teleca.se> wrote in message
news:uwxC2gaRFHA.1500@.TK2MSFTNGP09.phx.gbl...
> Hi,
> I have a select statement that gets data from only one table.
> When I write OPTION(LOOP JOIN) after this query and run it, the
> execution time is 2-3 times faster than without OPTION(LOOP JOIN).
> If I use OPTION(FAST 1) the execution time is as fast as with OPTION(LOOP
> JOIN)
> Does anyone know why its faster with nested loops join even though I don't
> join any tables?
> Thanks!
> //Malin
>|||The graphical execution plans are identical. (select <-- Clustered index
s)
If I have set showplan_text on there is a difference.
select col1, col2, col3
from table1
where col1=1234
option(loop join)
|--Clustered Index S(OBJECT:([DB].[dbo].[table1].[PK_tIndex]),
SEEK:([table1].[col1]=Convert([@.1])) ORDERED FORWARD)
select col1, col2, col3
from table1
where col1=1234
|--Clustered Index S(OBJECT:([DB].[dbo].[table1].[PK_tIndex]),
SEEK:([table1].[col1]=1234) ORDERED FORWARD)
Does "Convert([@.1])" have something to do with the execution time of the
query?
Thanks for helping.
// Malin
"Andrew J. Kelly" <sqlmvpnooospam@.shadhawk.com> wrote in message
news:eSqTusaRFHA.2604@.TK2MSFTNGP10.phx.gbl...
> Did you look at the actual execution plan to see what it is doing in both
> cases?
> --
> Andrew J. Kelly SQL MVP
>
> "Malin Davidsson" <malin.davidsson(at)aus.teleca.se> wrote in message
> news:uwxC2gaRFHA.1500@.TK2MSFTNGP09.phx.gbl...
>|||for instance, ...perhaps you have a couple of search arguments ANDed and SQL
Server can join these
by two indexes (aka index intersection) and this is the join which is influe
nced by your hint.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Andrew J. Kelly" <sqlmvpnooospam@.shadhawk.com> wrote in message
news:eSqTusaRFHA.2604@.TK2MSFTNGP10.phx.gbl...
> Did you look at the actual execution plan to see what it is doing in both
cases?
> --
> Andrew J. Kelly SQL MVP
>
> "Malin Davidsson" <malin.davidsson(at)aus.teleca.se> wrote in message
> news:uwxC2gaRFHA.1500@.TK2MSFTNGP09.phx.gbl...
>|||Hej :-),
I only have one argument in the where statement.
My query looks like "select col1, col2, col3 from table1 where col1=1234"
(as you probably already have seen in my previous message)
That's why I wonder where the "join" is?
// Malin
"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in
message news:%23LGPO7aRFHA.3928@.TK2MSFTNGP09.phx.gbl...
> for instance, ...perhaps you have a couple of search arguments ANDed and
> SQL Server can join these by two indexes (aka index intersection) and this
> is the join which is influenced by your hint.
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
>
> "Andrew J. Kelly" <sqlmvpnooospam@.shadhawk.com> wrote in message
> news:eSqTusaRFHA.2604@.TK2MSFTNGP10.phx.gbl...
>|||Hej. :-)
Strange... Did you look at the execution plan?
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Malin Davidsson" <malin.davidsson(at)aus.teleca.se> wrote in message
news:%23pJpeDbRFHA.3444@.tk2msftngp13.phx.gbl...
> Hej :-),
> I only have one argument in the where statement.
> My query looks like "select col1, col2, col3 from table1 where col1=1234"
(as you probably
> already have seen in my previous message)
> That's why I wonder where the "join" is?
> // Malin
>
> "Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote i
n message
> news:%23LGPO7aRFHA.3928@.TK2MSFTNGP09.phx.gbl...
>|||The graphical execution plans are identical. (select <-- Clustered index
s)
If I have set showplan_text on there is a difference.
select col1, col2, col3
from table1
where col1=1234
option(loop join)
|--Clustered Index S(OBJECT:([DB].[dbo].[table1].[PK_tIndex]),
SEEK:([table1].[col1]=Convert([@.1])) ORDERED FORWARD)
select col1, col2, col3
from table1
where col1=1234
|--Clustered Index S(OBJECT:([DB].[dbo].[table1].[PK_tIndex]),
SEEK:([table1].[col1]=1234) ORDERED FORWARD)
Does "Convert([@.1])" have something to do with the execution time of the
query?
Anything more I can do to find out what this can depend on?
// Malin
"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in
message news:eVHTpHbRFHA.3076@.tk2msftngp13.phx.gbl...
> Hej. :-)
> Strange... Did you look at the execution plan?
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
>
> "Malin Davidsson" <malin.davidsson(at)aus.teleca.se> wrote in message
> news:%23pJpeDbRFHA.3444@.tk2msftngp13.phx.gbl...
>|||In this example you have the value for Col1 as an integer. In the real
table is the datatype for Col1 an Integer?
Andrew J. Kelly SQL MVP
"Malin Davidsson" <malin.davidsson(at)aus.teleca.se> wrote in message
news:e0XLO5aRFHA.1172@.TK2MSFTNGP12.phx.gbl...
> The graphical execution plans are identical. (select <-- Clustered index
> s)
> If I have set showplan_text on there is a difference.
> select col1, col2, col3
> from table1
> where col1=1234
> option(loop join)
> |--Clustered Index S(OBJECT:([DB].[dbo].[table1].[PK_tIndex]),
> SEEK:([table1].[col1]=Convert([@.1])) ORDERED FORWARD)
>
> select col1, col2, col3
> from table1
> where col1=1234
> |--Clustered Index S(OBJECT:([DB].[dbo].[table1].[PK_tIndex]),
> SEEK:([table1].[col1]=1234) ORDERED FORWARD)
> Does "Convert([@.1])" have something to do with the execution time of the
> query?
> Thanks for helping.
> // Malin
>
> "Andrew J. Kelly" <sqlmvpnooospam@.shadhawk.com> wrote in message
> news:eSqTusaRFHA.2604@.TK2MSFTNGP10.phx.gbl...
>|||yes "col1" is an integer in the real table, the query looks exactly as I
have written except the names :-)
//Malin
"Andrew J. Kelly" <sqlmvpnooospam@.shadhawk.com> wrote in message
news:%23LZ9yTbRFHA.904@.tk2msftngp13.phx.gbl...
> In this example you have the value for Col1 as an integer. In the real
> table is the datatype for Col1 an Integer?
> --
> Andrew J. Kelly SQL MVP
>
> "Malin Davidsson" <malin.davidsson(at)aus.teleca.se> wrote in message
> news:e0XLO5aRFHA.1172@.TK2MSFTNGP12.phx.gbl...
>|||I will post to the internal group and see if anyone has seen this before.
Andrew J. Kelly SQL MVP
"Malin Davidsson" <malin.davidsson(at)aus.teleca.se> wrote in message
news:uvQUHabRFHA.3076@.TK2MSFTNGP14.phx.gbl...
> yes "col1" is an integer in the real table, the query looks exactly as I
> have written except the names :-)
> //Malin
> "Andrew J. Kelly" <sqlmvpnooospam@.shadhawk.com> wrote in message
> news:%23LZ9yTbRFHA.904@.tk2msftngp13.phx.gbl...
>

Nested loop SQL

Hi
I'm so new in SQL. I have SQL statement that nested loop.
That I don't like.
for example.
I have one table that keep Product Master
----------------
Table T_PRD_MS
----------------
COLUMN I_PRD_TYPE : primary key
I_PRD_ID : primary key
I_MANUF_DATE
I_EXPIRE_DATE
I_VENDOR_ID
I_BRAND_ID

And Other tables that keep Information about this product to readable format eg. T_PRD_TYPE -- > to get product type name
T_PRD_ID -- > to gett product name and detail

When I select data from table T_PRD_MS that in my criteria eg. Product that ID = '111'
I must to copy data to temp table for transaction up date. then I must to work in two steps.
1. select data from T_PRD_MS in criteria to TEMP table
2. use primary key in each row in TEMP table to get data record by record.

EG. sql = select * from T_PRD_MS where I_EXPIRE_DATE
= '20060210'
set SQL as recordset A
If recordset A not eof then
select data from T_PRD_ID where I_PRD_ID = recordset A.fields(0)
and I_PRD_TYPE = recordset A.fields(1)

How can I reduce my job for increase performance?Why not perform a SQL join?

select m.*, i.data
from T_PRD_MS m, T_PRD_ID i
where m.I_EXPIRE_DATE = '20060210'
and m.I_PRD_TYPE = i.I_PRD_TYPE;
and m.I_PRD_ID = i.I_PRD_ID;

Monday, March 12, 2012

Nested IIF statement in jump to URL function

Afternoon
I am trying to do a "jump to URL" expression that works as follows:
=IIF(isnothing( A FIELD ) , iif crm url etc etc...... , iif crm url etc etc
........)
But as yet can not get it to work.
Has anyone tryed something simular?
Thanks
Steve DAnother option would be likely to use a computed column when extracitng the
data...
Else it's best to tell us anyway waht is the result you hvae. It should
work.
--
Patrice
"Steve Dearman" <steve.dearman@.grant.co.uk> a écrit dans le message de news:
uUvrLGQpGHA.4116@.TK2MSFTNGP03.phx.gbl...
> Afternoon
> I am trying to do a "jump to URL" expression that works as follows:
> =IIF(isnothing( A FIELD ) , iif crm url etc etc...... , iif crm url etc
> etc ........)
> But as yet can not get it to work.
> Has anyone tryed something simular?
> Thanks
> Steve D
>|||I'm using the jump to Url box in the properties of the cell im using, when i
run the report i get no errors but also the link doesn't show up at all
which would point to my multiple iif statement being invalid for this use.
Anyone else managed to do this some other way?
"Patrice" <scribe@.chez.com> wrote in message
news:%238EWsTRpGHA.3584@.TK2MSFTNGP05.phx.gbl...
> Another option would be likely to use a computed column when extracitng
> the data...
> Else it's best to tell us anyway waht is the result you hvae. It should
> work.
> --
> Patrice
> "Steve Dearman" <steve.dearman@.grant.co.uk> a écrit dans le message de
> news: uUvrLGQpGHA.4116@.TK2MSFTNGP03.phx.gbl...
>> Afternoon
>> I am trying to do a "jump to URL" expression that works as follows:
>> =IIF(isnothing( A FIELD ) , iif crm url etc etc...... , iif crm url etc
>> etc ........)
>> But as yet can not get it to work.
>> Has anyone tryed something simular?
>> Thanks
>> Steve D
>|||I sorted it out my self, thanks anyway.
When your using more than one IIF statement in the jump to url property you
need to use the full field name eg.
First(Fields!'field name'.Value , " ' dataset name' ") other wise it wont
work.
May work without first but i have not tryed it.
Steve D
"Steve Dearman" <steve.dearman@.grant.co.uk> wrote in message
news:eLDlQTYpGHA.2400@.TK2MSFTNGP03.phx.gbl...
> I'm using the jump to Url box in the properties of the cell im using, when
> i run the report i get no errors but also the link doesn't show up at all
> which would point to my multiple iif statement being invalid for this use.
> Anyone else managed to do this some other way?
>
> "Patrice" <scribe@.chez.com> wrote in message
> news:%238EWsTRpGHA.3584@.TK2MSFTNGP05.phx.gbl...
>> Another option would be likely to use a computed column when extracitng
>> the data...
>> Else it's best to tell us anyway waht is the result you hvae. It should
>> work.
>> --
>> Patrice
>> "Steve Dearman" <steve.dearman@.grant.co.uk> a écrit dans le message de
>> news: uUvrLGQpGHA.4116@.TK2MSFTNGP03.phx.gbl...
>> Afternoon
>> I am trying to do a "jump to URL" expression that works as follows:
>> =IIF(isnothing( A FIELD ) , iif crm url etc etc...... , iif crm url etc
>> etc ........)
>> But as yet can not get it to work.
>> Has anyone tryed something simular?
>> Thanks
>> Steve D
>>
>

Nested IF statement and Declare problem

This is prolly more of a gut check, but needed to know if this looks right.
I am making another Scalar function..
CREATE FUNCTION [dbo].[EvalTradeCode]
(
@.tradeSymbol char(15)
)
RETURNS int(1)
AS
BEGIN
Declare @.intOffset int
If (left(tradesymbol, 1) = '@.')
If (isnumeric(left(right(tradesymbol, 6), 1))
@.intOffset = 1
If left(tradesymbol, 1) = '+'
If isnumeric(left(right(tradesymbol, 6), 1)
@.intOffset = 1
IF left(tradesymbol, 1) <>'@.' and left(tradesymbol, 1) <> '+'
If isnumeric(left(right(tradesymbol, 5), 1)
@.intOffset = 1
RETURN @.intOffset
END
I was getting an error because I was using the 'then' statement in there
(remember..i'm a VB programmer... and I did check out the bol site..lol)
I took the 'then' statements out. and now the only error that comes up is th
e:
'Oncorrect syntax near '@.intOffset' ' Error.
I'm not sure if this is because of the way that it's being used in the
function, or if i've got something bass ackwards.
Thanks for your input!
~Doc
www.krushradio.com - Internet Radio for the rest of usTry replacing
@.intOffset = 1
with
SET @.intOffset = 1
HTH
Vern
"Daniel Regalia" wrote:

> This is prolly more of a gut check, but needed to know if this looks right
.
> I am making another Scalar function..
> CREATE FUNCTION [dbo].[EvalTradeCode]
> (
> @.tradeSymbol char(15)
> )
> RETURNS int(1)
> AS
> BEGIN
> Declare @.intOffset int
> If (left(tradesymbol, 1) = '@.')
> If (isnumeric(left(right(tradesymbol, 6), 1))
> @.intOffset = 1
> If left(tradesymbol, 1) = '+'
> If isnumeric(left(right(tradesymbol, 6), 1)
> @.intOffset = 1
> IF left(tradesymbol, 1) <>'@.' and left(tradesymbol, 1) <> '+'
> If isnumeric(left(right(tradesymbol, 5), 1)
> @.intOffset = 1
> RETURN @.intOffset
> END
> I was getting an error because I was using the 'then' statement in there
> (remember..i'm a VB programmer... and I did check out the bol site..lol)
> I took the 'then' statements out. and now the only error that comes up is
the:
> 'Oncorrect syntax near '@.intOffset' ' Error.
> I'm not sure if this is because of the way that it's being used in the
> function, or if i've got something bass ackwards.
> Thanks for your input!
> ~Doc
> --
> www.krushradio.com - Internet Radio for the rest of us|||Not one.. there are lots of changes :)
no offences.
Here is the function.. Hope this helps.
CREATE FUNCTION [dbo].[EvalTradeCode]
(
@.tradeSymbol char(15)
)
RETURNS int
AS
BEGIN
Declare @.intOffset int
If (left(@.tradeSymbol, 1) = '@.')
If isnumeric(left(right(@.tradeSymbol, 6), 1)) = 1
set @.intOffset = 1
If left(@.tradeSymbol, 1) = '+'
If isnumeric(left(right(@.tradeSymbol, 6), 1)) = 1
set @.intOffset = 1
IF left(@.tradeSymbol, 1) <>'@.' and left(@.tradeSymbol, 1) <> '+'
If isnumeric(left(right(@.tradeSymbol, 5), 1)) = 1
set @.intOffset = 1
RETURN @.intOffset
END|||Gave it a shot....it didn't like it
Incorrect syntax near the keyword 'Set'
If (left(tradesymbol, 1) = '@.')
If (isnumeric(left(right(tradesymbol, 6), 1))
Set @.intOffset = 1
If left(tradesymbol, 1) = '+'
If isnumeric(left(right(tradesymbol, 6), 1)
Set @.intOffset = 1
IF left(tradesymbol, 1) <>'@.' and left(tradesymbol, 1) <> '+'
If isnumeric(left(right(tradesymbol, 5), 1)
Set @.intOffset = 1
--
www.krushradio.com - Internet Radio for the rest of us
"Vern Rabe" wrote:
> Try replacing
> @.intOffset = 1
> with
> SET @.intOffset = 1
> HTH
> Vern
> "Daniel Regalia" wrote:
>|||I feel it can better be written this way. You can validate better than me.
You should be a procedural logic expert :) Let me know.
CREATE FUNCTION [dbo].[EvalTradeCode]
(
@.tradeSymbol char(15)
)
RETURNS int
AS
BEGIN
Declare @.intOffset int
Set @.intOffset = 0
If (left(@.tradeSymbol, 1) = '@.') or (left(@.tradeSymbol, 1) = '+')
begin
If isnumeric(left(right(@.tradeSymbol, 6), 1)) = 1
set @.intOffset = 1
end
else
begin
If isnumeric(left(right(@.tradeSymbol, 5), 1)) = 1
set @.intOffset = 1
end
RETURN @.intOffset
END|||None Taken...
It's a learning experience for me :D. Just add this question to my beer
tab. Thanks OmniBuzz
~Doc
www.krushradio.com - Internet Radio for the rest of us
"Omnibuzz" wrote:

> Not one.. there are lots of changes :)
> no offences.
> Here is the function.. Hope this helps.
> CREATE FUNCTION [dbo].[EvalTradeCode]
> (
> @.tradeSymbol char(15)
> )
> RETURNS int
> AS
> BEGIN
> Declare @.intOffset int
> If (left(@.tradeSymbol, 1) = '@.')
> If isnumeric(left(right(@.tradeSymbol, 6), 1)) = 1
> set @.intOffset = 1
> If left(@.tradeSymbol, 1) = '+'
> If isnumeric(left(right(@.tradeSymbol, 6), 1)) = 1
> set @.intOffset = 1
> IF left(@.tradeSymbol, 1) <>'@.' and left(@.tradeSymbol, 1) <> '+'
> If isnumeric(left(right(@.tradeSymbol, 5), 1)) = 1
> set @.intOffset = 1
> RETURN @.intOffset
> END
>|||Sure Sir. I remember the first one you promised too..
Anything for a beer :)
"Daniel Regalia" wrote:
> None Taken...
> It's a learning experience for me :D. Just add this question to my beer
> tab. Thanks OmniBuzz
> ~Doc
>
> --
> www.krushradio.com - Internet Radio for the rest of us
>
> "Omnibuzz" wrote:
>|||One problem is that your parenthesis are not properly matching up. Another,
and this is just personal preference, is you are not using begin and end to
group your if else logic. I prefer to have a begin and end for every if
statement, and indent accordingly. It makes the code easier to follow, and
leaves no confusion as to the order of nested ifs.
"Daniel Regalia" <DanielRegalia@.discussions.microsoft.com> wrote in message
news:4618C615-2579-4999-B0BC-3DB935F7527F@.microsoft.com...
> This is prolly more of a gut check, but needed to know if this looks
right.
> I am making another Scalar function..
> CREATE FUNCTION [dbo].[EvalTradeCode]
> (
> @.tradeSymbol char(15)
> )
> RETURNS int(1)
> AS
> BEGIN
> Declare @.intOffset int
> If (left(tradesymbol, 1) = '@.')
> If (isnumeric(left(right(tradesymbol, 6), 1))
> @.intOffset = 1
> If left(tradesymbol, 1) = '+'
> If isnumeric(left(right(tradesymbol, 6), 1)
> @.intOffset = 1
> IF left(tradesymbol, 1) <>'@.' and left(tradesymbol, 1) <> '+'
> If isnumeric(left(right(tradesymbol, 5), 1)
> @.intOffset = 1
> RETURN @.intOffset
> END
> I was getting an error because I was using the 'then' statement in there
> (remember..i'm a VB programmer... and I did check out the bol site..lol)
> I took the 'then' statements out. and now the only error that comes up is
the:
> 'Oncorrect syntax near '@.intOffset' ' Error.
> I'm not sure if this is because of the way that it's being used in the
> function, or if i've got something bass ackwards.
> Thanks for your input!
> ~Doc
> --
> www.krushradio.com - Internet Radio for the rest of us

Nested Filters

Is it possible to create a complex, nested filter on a table in a report?
For example:
(Statement A AND Statement B) OR (Statement C AND Statement D)Hello Cindy,
Based on my experience, you could done this in another approach:
In the Filter of a table in reporting services, you type the nested filter
in the expression like this:
IIF( (Statement A AND Statement B) OR (Statement C AND Statement D) ,0,1)
Then, if the whole statement is true, the expression will return 0, and if
false, return 1.
Then, you could add "=0" (without quote) in the value column of the filter.
Hope this will be helpful!
Sincerely,
Wei Lu
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications.
Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
==================================================(This posting is provided "AS IS", with no warranties, and confers no
rights.)|||Hi ,
How is everything going? Please feel free to let me know if you need any
assistance.
Sincerely,
Wei Lu
Microsoft Online Community Support
==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================This posting is provided "AS IS" with no warranties, and confers no rights.

Nested case?

IS it possible to use nested case statement in TSQL,if yes what is the syntax of it

I m using SQL 2005

thanx

its possible...here is an example/syntax...

declare @.var1 int

declare @.var2 int

set @.var1 =1

set @.var2 =1

select

CASE @.var1

WHEN 1

THEN(

CASE @.var2

WHEN 1 THEN(

100)

ELSE 99

END)

ELSE 98

END

|||thanx very much.... this is the thing i asked for

Wednesday, March 7, 2012

need work around for if/then parsing problem

i'm writing a proc where i use an if/then statement to check a condition,
then create a temp table. the problem i'm having is that sql server seems to
think that the proc will attempt to create the same table twice. example:
if A
Select * Into #temp From Foo Where Bar = A
else
Select * Into #temp From Foo Where Bar <> A
How do you work around this?
Hi
You need to check whether the table already exists or not
if object_id('tempdb.dbo.#tem') is not null
begin
....
end
"ponhaus" <ponhaus@.discussions.microsoft.com> wrote in message
news:7B4F53C8-09D0-47C7-8F5A-22C7B30C17CD@.microsoft.com...
> i'm writing a proc where i use an if/then statement to check a condition,
> then create a temp table. the problem i'm having is that sql server seems
> to
> think that the proc will attempt to create the same table twice. example:
> if A
> Select * Into #temp From Foo Where Bar = A
> else
> Select * Into #temp From Foo Where Bar <> A
> How do you work around this?
|||I rewrote it as you suggest and it still reports error, "There is already an
object named '#Temp' in the database." Look at the example below to see if i
misunderstood what you were suggesting:
Declare @.A int
Set @.A = 0
if @.A = 0
begin
if object_id('tempdb.dbo.#Temp') is not null
Drop Table #Temp
Select * Into #Temp From Foo
end
else
begin
if object_id('tempdb.dbo.#Temp') is not null
Drop Table #Temp
Select * Into #Temp From Foo
end
|||Two options:
1) Create the temporary table (or table variable) using CREATE TABLE,
then use INSERT INTO in each section,
CREATE TABLE #Temp (<columns>)
If <condition>
INSERT INTO #Temp ...
Else
INSERT INTO #Temp ...
2) Create the temporary table structure first using SELECT * INTO...
then use INSERT INTO
SELECT * INTO #Temp From Foo Where 1 = 0
If <condition>
INSERT INTO ...
Else
INSERT INTO ...
I prefer option 1 because you have control over how the table is created
and what columns are going to be used, and you have the option (if the
table is small enough) of using a table variable instead of a temp table.
Jeff
ponhaus wrote:
I rewrote it as you suggest and it still reports error, "There is
already an
> object named '#Temp' in the database." Look at the example below to see if i
> misunderstood what you were suggesting:
> Declare @.A int
> Set @.A = 0
> if @.A = 0
> begin
> if object_id('tempdb.dbo.#Temp') is not null
> Drop Table #Temp
> Select * Into #Temp From Foo
> end
> else
> begin
> if object_id('tempdb.dbo.#Temp') is not null
> Drop Table #Temp
> Select * Into #Temp From Foo
> end
>
|||Thanks,
I ended up using a variation on #2, "Select top 0 From Foo"...but I was
really hoping for a way to sidestep the bug in the interpreter, like turning
off all checking.
|||select
*
into #temp
from foo
where (@.flag=1 and bar = A)
or
(@.flag=0 and bar <> A)
lotta code like that lying around.
J.
On Tue, 6 Mar 2007 05:53:00 -0800, ponhaus
<ponhaus@.discussions.microsoft.com> wrote:

>i'm writing a proc where i use an if/then statement to check a condition,
>then create a temp table. the problem i'm having is that sql server seems to
>think that the proc will attempt to create the same table twice. example:
>if A
> Select * Into #temp From Foo Where Bar = A
>else
> Select * Into #temp From Foo Where Bar <> A
>How do you work around this?

need work around for if/then parsing problem

i'm writing a proc where i use an if/then statement to check a condition,
then create a temp table. the problem i'm having is that sql server seems to
think that the proc will attempt to create the same table twice. example:
if A
Select * Into #temp From Foo Where Bar = A
else
Select * Into #temp From Foo Where Bar <> A
How do you work around this?Hi
You need to check whether the table already exists or not
if object_id('tempdb.dbo.#tem') is not null
begin
...
end
"ponhaus" <ponhaus@.discussions.microsoft.com> wrote in message
news:7B4F53C8-09D0-47C7-8F5A-22C7B30C17CD@.microsoft.com...
> i'm writing a proc where i use an if/then statement to check a condition,
> then create a temp table. the problem i'm having is that sql server seems
> to
> think that the proc will attempt to create the same table twice. example:
> if A
> Select * Into #temp From Foo Where Bar = A
> else
> Select * Into #temp From Foo Where Bar <> A
> How do you work around this?|||I rewrote it as you suggest and it still reports error, "There is already an
object named '#Temp' in the database." Look at the example below to see if i
misunderstood what you were suggesting:
Declare @.A int
Set @.A = 0
if @.A = 0
begin
if object_id('tempdb.dbo.#Temp') is not null
Drop Table #Temp
Select * Into #Temp From Foo
end
else
begin
if object_id('tempdb.dbo.#Temp') is not null
Drop Table #Temp
Select * Into #Temp From Foo
end|||Two options:
1) Create the temporary table (or table variable) using CREATE TABLE,
then use INSERT INTO in each section,
CREATE TABLE #Temp (<columns>)
If <condition>
INSERT INTO #Temp ...
Else
INSERT INTO #Temp ...
2) Create the temporary table structure first using SELECT * INTO...
then use INSERT INTO
SELECT * INTO #Temp From Foo Where 1 = 0
If <condition>
INSERT INTO ...
Else
INSERT INTO ...
I prefer option 1 because you have control over how the table is created
and what columns are going to be used, and you have the option (if the
table is small enough) of using a table variable instead of a temp table.
Jeff
ponhaus wrote:
I rewrote it as you suggest and it still reports error, "There is
already an
> object named '#Temp' in the database." Look at the example below to see if i
> misunderstood what you were suggesting:
> Declare @.A int
> Set @.A = 0
> if @.A = 0
> begin
> if object_id('tempdb.dbo.#Temp') is not null
> Drop Table #Temp
> Select * Into #Temp From Foo
> end
> else
> begin
> if object_id('tempdb.dbo.#Temp') is not null
> Drop Table #Temp
> Select * Into #Temp From Foo
> end
>|||Thanks,
I ended up using a variation on #2, "Select top 0 From Foo"...but I was
really hoping for a way to sidestep the bug in the interpreter, like turning
off all checking.|||select
*
into #temp
from foo
where (@.flag=1 and bar = A)
or
(@.flag=0 and bar <> A)
lotta code like that lying around.
J.
On Tue, 6 Mar 2007 05:53:00 -0800, ponhaus
<ponhaus@.discussions.microsoft.com> wrote:
>i'm writing a proc where i use an if/then statement to check a condition,
>then create a temp table. the problem i'm having is that sql server seems to
>think that the proc will attempt to create the same table twice. example:
>if A
> Select * Into #temp From Foo Where Bar = A
>else
> Select * Into #temp From Foo Where Bar <> A
>How do you work around this?

need work around for if/then parsing problem

i'm writing a proc where i use an if/then statement to check a condition,
then create a temp table. the problem i'm having is that sql server seems to
think that the proc will attempt to create the same table twice. example:
if A
Select * Into #temp From Foo Where Bar = A
else
Select * Into #temp From Foo Where Bar <> A
How do you work around this?Hi
You need to check whether the table already exists or not
if object_id('tempdb.dbo.#tem') is not null
begin
...
end
"ponhaus" <ponhaus@.discussions.microsoft.com> wrote in message
news:7B4F53C8-09D0-47C7-8F5A-22C7B30C17CD@.microsoft.com...
> i'm writing a proc where i use an if/then statement to check a condition,
> then create a temp table. the problem i'm having is that sql server seems
> to
> think that the proc will attempt to create the same table twice. example:
> if A
> Select * Into #temp From Foo Where Bar = A
> else
> Select * Into #temp From Foo Where Bar <> A
> How do you work around this?|||I rewrote it as you suggest and it still reports error, "There is already an
object named '#Temp' in the database." Look at the example below to see if i
misunderstood what you were suggesting:
Declare @.A int
Set @.A = 0
if @.A = 0
begin
if object_id('tempdb.dbo.#Temp') is not null
Drop Table #Temp
Select * Into #Temp From Foo
end
else
begin
if object_id('tempdb.dbo.#Temp') is not null
Drop Table #Temp
Select * Into #Temp From Foo
end|||Two options:
1) Create the temporary table (or table variable) using CREATE TABLE,
then use INSERT INTO in each section,
CREATE TABLE #Temp (<columns> )
If <condition>
INSERT INTO #Temp ...
Else
INSERT INTO #Temp ...
2) Create the temporary table structure first using SELECT * INTO...
then use INSERT INTO
SELECT * INTO #Temp From Foo Where 1 = 0
If <condition>
INSERT INTO ...
Else
INSERT INTO ...
I prefer option 1 because you have control over how the table is created
and what columns are going to be used, and you have the option (if the
table is small enough) of using a table variable instead of a temp table.
Jeff
ponhaus wrote:
I rewrote it as you suggest and it still reports error, "There is
already an
> object named '#Temp' in the database." Look at the example below to see if
i
> misunderstood what you were suggesting:
> Declare @.A int
> Set @.A = 0
> if @.A = 0
> begin
> if object_id('tempdb.dbo.#Temp') is not null
> Drop Table #Temp
> Select * Into #Temp From Foo
> end
> else
> begin
> if object_id('tempdb.dbo.#Temp') is not null
> Drop Table #Temp
> Select * Into #Temp From Foo
> end
>|||Thanks,
I ended up using a variation on #2, "Select top 0 From Foo"...but I was
really hoping for a way to sidestep the bug in the interpreter, like turning
off all checking.|||select
*
into #temp
from foo
where (@.flag=1 and bar = A)
or
(@.flag=0 and bar <> A)
lotta code like that lying around.
J.
On Tue, 6 Mar 2007 05:53:00 -0800, ponhaus
<ponhaus@.discussions.microsoft.com> wrote:

>i'm writing a proc where i use an if/then statement to check a condition,
>then create a temp table. the problem i'm having is that sql server seems t
o
>think that the proc will attempt to create the same table twice. example:
>if A
> Select * Into #temp From Foo Where Bar = A
>else
> Select * Into #temp From Foo Where Bar <> A
>How do you work around this?

Monday, February 20, 2012

Need to use MID function in SQL

When I try to use the MID statement in a SQL view, it reports 'function not recognized'. Is there some other way to execute the following?

CASE WHEN Mid(SearchID , 4 , 1) = '-' THEN LEFT (SearchID , 3) ELSE LEFT (SearchID , 4) END.

I have a column with two data set possibilities: aaa-bbbbb and aaaa-bbbbb. I only want the data to the left of the dash.

Thanks.

Ernie

You have to combine sql sever string function

like "left" and "right" to achive you requirements

I think the equivalent of vb mid function is the "substring" function

This example shows how to return only a portion of a character string. From the authors table, this query returns the last name in one column with only the first initial in the second column.

USE pubs SELECT au_lname, SUBSTRING(au_fname, 1, 1) FROM authors ORDER BY au_lname 
|||

create table #test (SearchID varchar(49))
insert into #test values('aaa-bbbbb')
insert into #test values('aaaa-bbbbb')

one way using ParseName
Select ParseName(Replace(SearchID , '-', '.'), 2)
from #test


and another using left and charindex
select distinct LEFT(SearchID ,CHARINDEX('-',SearchID )-1 )
from #test

and a third using case substring and left
select CASE substring(SearchID , 4 , 1) when '-' THEN LEFT (SearchID , 3) ELSE LEFT (SearchID , 4) END
from #test

Denis the SQL Menace
http://sqlservercode.blogspot.com/

|||Thanks! I appreciate the help.