Showing posts with label column. Show all posts
Showing posts with label column. Show all posts

Friday, March 30, 2012

Query XML type with values from another XML type

Hi - I'm using SQL Server 2005, and I have a view with an XML data type column. I would like to write a stored proc that takes an XML data type as a parameter and return the rows from the view that match the columns in the parameter.

At this point, I'm just trying to get the syntax correct, so I started with some simple queries. Below are the queries:

declare @.params xml

declare @.view xml

set @.params = '<HierarchyTypes>

<HierarchyType hierarchyTypeId="4" />

<HierarchyType hierarchyTypeId="5" />

</HierarchyTypes>'

set @.view = '<HierarchyTypes>

<HierarchyType hierarchyTypeId="4" otherProp = "1"/>

<HierarchyType hierarchyTypeId="5" otherProp = "2"/>

<HierarchyType hierarchyTypeId="6" otherProp = "3"/>

<HierarchyType hierarchyTypeId="7" otherProp = "4"/>

</HierarchyTypes>'

SELECT T.c.query('.') AS result

FROM @.view.nodes('/HierarchyTypes/HierarchyType') T(c)

I would like to get the nodes from @.view where @.view.hierarchyTypeId = @.params.hierarchyTypeId. This should be pretty simple, but I'm missing it...

Any thoughts are appreciated!

Thanks,

Phil

It sounds like you are trying to join view and params to get a results set which has one matching node per row. If that is the case, the below query should be doing what you are looking for. If you want to return a single xml fragment, a different technique would have to be used.

In the query below, we iterate over the HierarchyType nodes of both @.view and @.params, project the values of the hierarchyTypeId attributes as integers using the the value() function, verify that they match, and the return the @.param node that matches.

declare @.params xml
declare @.view xml

set @.params = '<HierarchyTypes>
<HierarchyType hierarchyTypeId="4" />
<HierarchyType hierarchyTypeId="5" />
</HierarchyTypes>'

set @.view = '<HierarchyTypes>
<HierarchyType hierarchyTypeId="4" otherProp = "1"/>
<HierarchyType hierarchyTypeId="5" otherProp = "2"/>
<HierarchyType hierarchyTypeId="6" otherProp = "3"/>
<HierarchyType hierarchyTypeId="7" otherProp = "4"/>
</HierarchyTypes>'

SELECT T.c.query('.') AS result
FROM @.view.nodes('/HierarchyTypes/HierarchyType') T(c),

@.params.nodes('/HierarchyTypes/HierarchyType') P(c)
WHERE T.c.value('@.hierarchyTypeId', 'int') = P.c.value('@.hierarchyTypeId', 'int')

|||

Hi Todd - this is very close to what I need. The only other wrinkle is that I'm trying to select all of the columns from the view (not just the hierarchyTypeId). The view has an XML column called HierarchyTypes, and I want to use that column in my 'join criteria'. And I'd like to do this in a stored proc.

CREATE PROCEDURE [dbo].[CodeHierarchy_SearchHierarchy]
@.codeTypes xml = NULL
AS
BEGIN
SET NOCOUNT ON;
SELECT v.nodeId,
v.parentNodeId,
v.HierarchyTypes
FROM VLinkedCodeHierarchies as v
WHERE /* hierarchyTypes in @.codeTypes are also in v.HierarchyTypes */

At this point, I also require that the return is NOT XML.

Thanks,

Phil

|||

So it sounds like you have a table or a view that has a few relational columns, and 1 xml column. And then you want to join it with an XML fragment.

Is that correct?

If so, then you can modify the query to use CROSS APPLY. In the example I create a test table which has an xml column, fill it with data and then join it with the fragment, projecting the relevant relational columns and xml data. You could then wrap it in a stored procedure or user defined function as needed.

(I CROSS APPLY the vTest table with nodes() function so that I get the nodes for the current row.)

declare @.params xml

drop table vTest
Create table vTest(
id int,
val xml
)


insert into vTest (id, val) values (1,'<HierarchyTypes>
<HierarchyType hierarchyTypeId="4" otherProp = "1"/>
<HierarchyType hierarchyTypeId="5" otherProp = "2"/>
<HierarchyType hierarchyTypeId="6" otherProp = "3"/>
<HierarchyType hierarchyTypeId="7" otherProp = "4"/>
</HierarchyTypes>')


insert into vTest (id, val) values (2,'<HierarchyTypes>
<HierarchyType hierarchyTypeId="8" otherProp = "1"/>
<HierarchyType hierarchyTypeId="9" otherProp = "2"/>
<HierarchyType hierarchyTypeId="10" otherProp = "3"/>
<HierarchyType hierarchyTypeId="11" otherProp = "4"/>
</HierarchyTypes>')


set @.params = '<HierarchyTypes>
<HierarchyType hierarchyTypeId="4" />
<HierarchyType hierarchyTypeId="5" />
<HierarchyType hierarchyTypeId="11" />
</HierarchyTypes>'

SELECT vTable.Id,
xVal.c.value('@.hierarchyTypeId', 'int') as hierarchyTypeId,
xVal.c.value('@.otherProp', 'int') as otherProp,
xVal.c.query('.') as MatchingFragment

FROM @.params.nodes('/HierarchyTypes/HierarchyType') P(c),
vTest as vTable CROSS APPLY vTable.Val.nodes('/HierarchyTypes/HierarchyType') xVal(c)
WHERE xVal.c.value('@.hierarchyTypeId', 'int') = P.c.value('@.hierarchyTypeId', 'int')

If you dont want to Join the parameter fragment and the table, but just want to check that for each row it's xml column has some data in common with the parameter fragment, then you could change the query to use an EXISTS.

|||

Hi Todd - thanks again for the excellent reply. I actually want to make sure that the rows returned have data in common with the XML fragment.

Ideally, I would like to have 3 options:

1) View column has some data from XML fragement

2) View column has all data from XML fragment, but could have more.

3) View column has ONLY data from XML fragement.

I can accomplish #1 above using a SELECT DISTINCT, but I don't think that's the most optimum.

Where are some good resources to educate myself on this?

Thanks!

Phil

|||

Here is where you can find the the basics of XQuery and the T-SQL functions that support it:
http://msdn2.microsoft.com/en-us/library/ms190262.aspx

The current w3c resources:
http://www.w3.org/TR/xquery/

T-SQL Reference:
http://msdn2.microsoft.com/en-us/library/ms189826.aspx

And there are probably a number of tutorials that would discuss the differences of when to use a DISTINCT vs EXISTS vs CROSS APPLY.

query xml datatype

In SQL 2005, we've defined a column as type "xml". We'd like to query
that column so that its nodes are returned in traditional columnar
format. For instance, to get the first & last name nodes, we have code
like...
Select cast(Info.query('
declare namespace m="http://tempuri.org/MyInfo";
data(/m:info/m:firstname)') as varchar(200)) as FirstName,
cast(Info.query('
declare namespace m="http://tempuri.org/MyInfo";
data(/m:info/m:lastname)') as varchar(200)) as LastName
from MyTest
That seems like a lot of work to get the first & last name in columnar
format. Is there a better way to do this?
You can't write it a whole lot simpler.
Here's what I would write if firstname and lastname elements have open
content:
WITH XMLNAMESPACES('http://tempuri.org/MyInfo' AS m)
SELECT
Info.value('(/m:info/m:firstname/text())[1]','varchar(200)') AS
FirstName,
Info.value('(/m:info/m:lastname/text())[1]','varchar(200)') AS LastName
FROM MyTest
Note that value() method does both atomization (data()) of the resulting
XQuery sequence element (must be singleton) and mapping it to a SQL type
provided as the 2nd parameter.
If your XML column is typed and firstname and lastname elements have simple
type/content than you'd need to remove "/text()" from the above XQuery
expressions.
Note that if there could be multiple firstname/lastname elements per XML
instance and you needed each of them on a separate row you'd use nodes()
method in FROM clause.
Regards,
Eugene
This posting is provided "AS IS" with no warranties, and confers no rights.
"--Marty" <Martin.McDonald@.us.logicalis.com> wrote in message
news:1126718758.082803.55550@.g47g2000cwa.googlegro ups.com...
> In SQL 2005, we've defined a column as type "xml". We'd like to query
> that column so that its nodes are returned in traditional columnar
> format. For instance, to get the first & last name nodes, we have code
> like...
> Select cast(Info.query('
> declare namespace m="http://tempuri.org/MyInfo";
> data(/m:info/m:firstname)') as varchar(200)) as FirstName,
> cast(Info.query('
> declare namespace m="http://tempuri.org/MyInfo";
> data(/m:info/m:lastname)') as varchar(200)) as LastName
> from MyTest
> That seems like a lot of work to get the first & last name in columnar
> format. Is there a better way to do this?
>

query xml datatype

In SQL 2005, we've defined a column as type "xml". We'd like to query
that column so that its nodes are returned in traditional columnar
format. For instance, to get the first & last name nodes, we have code
like...
Select cast(Info.query('
declare namespace m="http://tempuri.org/MyInfo";
data(/m:info/m:firstname)') as varchar(200)) as FirstName,
cast(Info.query('
declare namespace m="http://tempuri.org/MyInfo";
data(/m:info/m:lastname)') as varchar(200)) as LastName
from MyTest
That seems like a lot of work to get the first & last name in columnar
format. Is there a better way to do this?You can't write it a whole lot simpler.
Here's what I would write if firstname and lastname elements have open
content:
WITH XMLNAMESPACES('http://tempuri.org/MyInfo' AS m)
SELECT
Info.value('(/m:info/m:firstname/text())[1]','varchar(200)') AS
FirstName,
Info.value('(/m:info/m:lastname/text())[1]','varchar(200)') AS LastName
FROM MyTest
Note that value() method does both atomization (data()) of the resulting
XQuery sequence element (must be singleton) and mapping it to a SQL type
provided as the 2nd parameter.
If your XML column is typed and firstname and lastname elements have simple
type/content than you'd need to remove "/text()" from the above XQuery
expressions.
Note that if there could be multiple firstname/lastname elements per XML
instance and you needed each of them on a separate row you'd use nodes()
method in FROM clause.
Regards,
Eugene
--
This posting is provided "AS IS" with no warranties, and confers no rights.
"--Marty" <Martin.McDonald@.us.logicalis.com> wrote in message
news:1126718758.082803.55550@.g47g2000cwa.googlegroups.com...
> In SQL 2005, we've defined a column as type "xml". We'd like to query
> that column so that its nodes are returned in traditional columnar
> format. For instance, to get the first & last name nodes, we have code
> like...
> Select cast(Info.query('
> declare namespace m="http://tempuri.org/MyInfo";
> data(/m:info/m:firstname)') as varchar(200)) as FirstName,
> cast(Info.query('
> declare namespace m="http://tempuri.org/MyInfo";
> data(/m:info/m:lastname)') as varchar(200)) as LastName
> from MyTest
> That seems like a lot of work to get the first & last name in columnar
> format. Is there a better way to do this?
>

Wednesday, March 28, 2012

Query with user-define function John Bell

Yes!! It works. But just a point. In the [Index] column I have both strings
and numbers. When I query [Index]=AA there is an error: Invalid column name
'AA'
Any more suggestion?
Thank you
Helen
"John Bell" wrote:

> Hi
> Maybe
> CREATE TABLE foo ( [index] int not null identity(1,1), a int, b int, c
> varchar(10) )
> INSERT INTO Foo ( a, b, c ) SELECT 5,9,'a+@.q+3*b'
> DECLARE @.sql VARCHAR(255)
> SELECT @.sql = 'DECLARE @.q int SET @.q=7 SELECT a,b,' + c+ ' FROM dbo.foo
> where [Index]=1'
> FROM dbo.foo where [Index]=1
> EXEC(@.sql)
> John[Index] = 'AA'.
Perayu
"Helen" <Helen@.discussions.microsoft.com> wrote in message
news:A76F8AD0-7065-4968-ADA5-9E957DD7949D@.microsoft.com...
> Yes!! It works. But just a point. In the [Index] column I have both
> strings
> and numbers. When I query [Index]=AA there is an error: Invalid column
> name
> 'AA'
> Any more suggestion?
> Thank you
> Helen
> "John Bell" wrote:
>
>

Query with user-define function John Bell

Yes!! It works. But just a point. In the [Index] column I have both strings
and numbers. When I query [Index]=AA there is an error: Invalid column name
'AA'
Any more suggestion?
Thank you
Helen
"John Bell" wrote:

> Hi
> Maybe
> CREATE TABLE foo ( [index] int not null identity(1,1), a int, b int, c
> varchar(10) )
> INSERT INTO Foo ( a, b, c ) SELECT 5,9,'a+@.q+3*b'
> DECLARE @.sql VARCHAR(255)
> SELECT @.sql = 'DECLARE @.q int SET @.q=7 SELECT a,b,' + c+ ' FROM dbo.foo
> where [Index]=1'
> FROM dbo.foo where [Index]=1
> EXEC(@.sql)
> John
>
> "Helen" <Helen@.discussions.microsoft.com> wrote in message
> news:A3A0BB12-2B9D-4173-81B3-F17D30F6D59B@.microsoft.com...
>
>Hi
If your column is a character datatype use 'AA' As quotes will require
escaping with a second quote within the string you end up with:
CREATE TABLE foo ( [index] CHAR(2) not null , a int, b int, c
varchar(10) )
INSERT INTO Foo ( [Index],a, b, c ) SELECT 'AA',5,9,'a+@.q+(3*b)'
DECLARE @.sql VARCHAR(255)
SELECT @.sql = 'DECLARE @.q int SET @.q=7 SELECT a,b,' + c+ ' FROM dbo.foo
where [Index]=''AA'''
FROM dbo.foo where [Index]='AA'
EXEC(@.sql)
John
"Helen" <Helen@.discussions.microsoft.com> wrote in message
news:196B3526-043F-40E1-9BD5-F1D6669C093A@.microsoft.com...
> Yes!! It works. But just a point. In the [Index] column I have both
> strings
> and numbers. When I query [Index]=AA there is an error: Invalid column
> name
> 'AA'
> Any more suggestion?
> Thank you
> Helen
> "John Bell" wrote:
>|||Yes!!! It is all right now. I wonder how to write this in visualbasic.net
Thanks
Helen
"John Bell" wrote:

> Hi
> If your column is a character datatype use 'AA' As quotes will require
> escaping with a second quote within the string you end up with:
> CREATE TABLE foo ( [index] CHAR(2) not null , a int, b int, c
> varchar(10) )
> INSERT INTO Foo ( [Index],a, b, c ) SELECT 'AA',5,9,'a+@.q+(3*b)'
> DECLARE @.sql VARCHAR(255)
> SELECT @.sql = 'DECLARE @.q int SET @.q=7 SELECT a,b,' + c+ ' FROM dbo.foo
> where [Index]=''AA'''
> FROM dbo.foo where [Index]='AA'
> EXEC(@.sql)
> John
> "Helen" <Helen@.discussions.microsoft.com> wrote in message
> news:196B3526-043F-40E1-9BD5-F1D6669C093A@.microsoft.com...
>
>

Monday, March 26, 2012

query with a column per row of a linked table - dynamic sql

I've thought about this a bit more and relised that it can be done using
dynamic SQL, but I would like to avoid this if possible. What are the other
options?
"WCL" <WCL@.nospam.nospam> wrote in message
news:usRAcZGIGHA.1312@.TK2MSFTNGP09.phx.gbl...
> Is it possible to have query result to have a column per row of a table?
>
> e.g.
> Employees table
> ID (identity)
> FirstName
> Ref
>
> containing
> ID, FirstName
> 1 Tom
> 2 Dick
> 3 Harry
>
>
> Project table
> ID (identity)
> Name
>
> containing
> ID, Name
> 1 Client A
> 2 Client B
> 3 Client C
>
> Timesheets
> ID (identity)
> Employees_ID
> Project_ID
> Hours
>
> containing 6 rows
> ID
> Employee_ID
> Project_ID
> Hours
> 1
> 1
> 1
> 5
> 2
> 1
> 2
> 15
> 3
> 2
> 1
> 2
> 4
> 2
> 2
> 4
> 5
> 3
> 1
> 8
> 6
> 3
> 2
> 8
>
> NB - No records for client C
>
> I can get three columns (name, client, hours) with nine rows no problem,
> but how do I get 3 rows with a column per Client, like this:?
>
> Name
> Client A
> Client B
> Client C
> Tom
> 5
> 15
> 0 or NULL
> Dick
> 2
> 4
> 0 or NULL
> Harry
> 8
> 8
> 0 or NULL
>
>
>No, it is not really useful from a SQL standpoint to do this, so it is not a
part of SQL (columns should contain like things, not multiple different
things.)
I think you can do it using several UNION ALLs:
SELECT client, cast(client as varchar(30)), 1 as sorting
FROM table
UNION ALL
SELECT client,cast(value1 as varchar(30)), 2 as sorting
FROM table
order by client, sorting --maybe something different than key
I would suggest using the client tool to format data like this.
----
Louis Davidson - http://spaces.msn.com/members/drsql/
SQL Server MVP
"Arguments are to be avoided: they are always vulgar and often convincing."
(Oscar Wilde)
"WCL" <WCL@.nospam.nospam> wrote in message
news:u4q6ipGIGHA.3176@.TK2MSFTNGP12.phx.gbl...
> I've thought about this a bit more and relised that it can be done using
> dynamic SQL, but I would like to avoid this if possible. What are the
> other options?
> "WCL" <WCL@.nospam.nospam> wrote in message
> news:usRAcZGIGHA.1312@.TK2MSFTNGP09.phx.gbl...
>

query with a column per row of a linked table

Is it possible to have query result to have a column per row of a table?
e.g.
Employees table
ID (identity)
FirstName
Ref
containing
ID, FirstName
1 Tom
2 Dick
3 Harry
Project table
ID (identity)
Name
containing
ID, Name
1 Client A
2 Client B
3 Client C
Timesheets
ID (identity)
Employees_ID
Project_ID
Hours
containing 6 rows
ID
Employee_ID
Project_ID
Hours
1
1
1
5
2
1
2
15
3
2
1
2
4
2
2
4
5
3
1
8
6
3
2
8
NB - No records for client C
I can get three columns (name, client, hours) with nine rows no problem, but
how do I get 3 rows with a column per Client, like this:?
Name
Client A
Client B
Client C
Tom
5
15
0 or NULL
Dick
2
4
0 or NULL
Harry
8
8
0 or NULLWCL wrote:
> Is it possible to have query result to have a column per row of a table?
This is a common problem, known as "crosstab query" (hint: Google that).
First, you will want to read this:
http://www.stephenforte.net/owdasbl...>
15d6d813eeb8
This is harder to do when the number of ouput columns isn't static. I am
not aware of any ways to do that without dynamic SQL on SQL Server 2000 and
below. SQL Server 2005 provides PIVOT functionality -- which I have yet to
play with myself, but believe does exactly that.
Chris Priede|||"Chris Priede" <priede@.panix.com> wrote in message
news:%235a8RMHIGHA.676@.TK2MSFTNGP10.phx.gbl...
> WCL wrote:
> This is a common problem, known as "crosstab query" (hint: Google that).
> First, you will want to read this:
>
http://www.stephenforte.net/owdasbl...>
15d6d813eeb8
I do not think this is the CASE at all:)

> This is harder to do when the number of ouput columns isn't static. I am
> not aware of any ways to do that without dynamic SQL on SQL Server 2000
and
> below. SQL Server 2005 provides PIVOT functionality -- which I have yet
to
> play with myself, but believe does exactly that.
You be confusing your 'belief' with your 'wish':)
An alternative may be found @.
www.rac4sql.net|||Hi,
05ponyGT wrote:
> I do not think this is the CASE at all:)
> You be confusing your 'belief' with your 'wish':)
> An alternative may be found @.
> www.rac4sql.net
The absence of any technical insight to accompany your assertions led me to
Google your posting name. Of the 11 results returned, 11 are pushing this
particular product.
In addition, I couldn't help but notice that both the Rac "F.A.Q." and "What
can Rac do" section of documentation suffer from multiple instances of
incorrect usage of "your" vs. "you're", as well as other grammatical
sloppyness. It may help your advertising efforts to fix those first. :)
Chris Priede|||"Chris Priede" <priede@.panix.com> wrote in message
news:O7kZP3HIGHA.2472@.TK2MSFTNGP10.phx.gbl...
> Hi,
> 05ponyGT wrote:
> The absence of any technical insight to accompany your assertions led me
to
> Google your posting name. Of the 11 results returned, 11 are pushing this
> particular product.
That is extremely thin!
I'm aware my reply may have been a bit ponderous but just what
didn't you understand?Talk about insight:)

> In addition, I couldn't help but notice that both the Rac "F.A.Q." and
"What
> can Rac do" section of documentation suffer from multiple instances of
> incorrect usage of "your" vs. "you're", as well as other grammatical
> sloppyness. It may help your advertising efforts to fix those first. :)
You are right.Content always comes in second:)|||> http://www.stephenforte.net/owdasbl...
5-15d6d813eeb8
vey usefull link , then I googled for 'crosstab query.
Found some info on a 'dynamic cross tab', I'll give it a go and post with
the results.
"Chris Priede" <priede@.panix.com> wrote in message
news:%235a8RMHIGHA.676@.TK2MSFTNGP10.phx.gbl...
> WCL wrote:
> This is a common problem, known as "crosstab query" (hint: Google that).
> First, you will want to read this:
> http://www.stephenforte.net/owdasbl...
5-15d6d813eeb8
> This is harder to do when the number of ouput columns isn't static. I am
> not aware of any ways to do that without dynamic SQL on SQL Server 2000
> and below. SQL Server 2005 provides PIVOT functionality -- which I have
> yet to play with myself, but believe does exactly that.
>
> --
> Chris Priede
>

Query where feild name is reserved

Using query analyzer, how can I return a column (desc in this case)
that is also a reserved word?
I'm working with a commercial product so I can't change the name of
the column.
I've tried things like:
Select desc from foo
Select 'desc' from foo
select id,desc from foo
etc...
each one gives me: Error near reserved word 'desc'
Thanks.
When encountering any object name that is a reserved word, enclose it in
either double quotes, or square brackets.
"desc" or [desc]
And when you use multiple part names, such as:
MyDatabase.dbo.Table
enclose on the reserved word part of the name in delimiters:
MyDatabase.dbo.[Table]
Arnie Rowland, Ph.D.
Westwood Consulting, Inc
Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous
You can't help someone get up a hill without getting a little closer to the
top yourself.
- H. Norman Schwarzkopf
<Scamp@.nospam.com> wrote in message
news:i187l2tkup4aols7dv9kvbr4gfjd51626t@.4ax.com...
> Using query analyzer, how can I return a column (desc in this case)
> that is also a reserved word?
> I'm working with a commercial product so I can't change the name of
> the column.
> I've tried things like:
> Select desc from foo
> Select 'desc' from foo
> select id,desc from foo
> etc...
> each one gives me: Error near reserved word 'desc'
>
> Thanks.
>

Query where feild name is reserved

Using query analyzer, how can I return a column (desc in this case)
that is also a reserved word?
I'm working with a commercial product so I can't change the name of
the column.
I've tried things like:
Select desc from foo
Select 'desc' from foo
select id,desc from foo
etc...
each one gives me: Error near reserved word 'desc'
Thanks.ANSI SQL compliant:
SELECT "desc" FROM foo
SQL Server specific:
SELECT [desc] FROM foo
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
<Scamp@.nospam.com> wrote in message news:i187l2tkup4aols7dv9kvbr4gfjd51626t@.4ax.com...
> Using query analyzer, how can I return a column (desc in this case)
> that is also a reserved word?
> I'm working with a commercial product so I can't change the name of
> the column.
> I've tried things like:
> Select desc from foo
> Select 'desc' from foo
> select id,desc from foo
> etc...
> each one gives me: Error near reserved word 'desc'
>
> Thanks.
>|||When encountering any object name that is a reserved word, enclose it in
either double quotes, or square brackets.
"desc" or [desc]
And when you use multiple part names, such as:
MyDatabase.dbo.Table
enclose on the reserved word part of the name in delimiters:
MyDatabase.dbo.[Table]
--
Arnie Rowland, Ph.D.
Westwood Consulting, Inc
Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous
You can't help someone get up a hill without getting a little closer to the
top yourself.
- H. Norman Schwarzkopf
<Scamp@.nospam.com> wrote in message
news:i187l2tkup4aols7dv9kvbr4gfjd51626t@.4ax.com...
> Using query analyzer, how can I return a column (desc in this case)
> that is also a reserved word?
> I'm working with a commercial product so I can't change the name of
> the column.
> I've tried things like:
> Select desc from foo
> Select 'desc' from foo
> select id,desc from foo
> etc...
> each one gives me: Error near reserved word 'desc'
>
> Thanks.
>sql

query w/ case help

Hey all, here is my problem: I want to run a query to grab all the 'next dates' from a column after the user inputs a date. .. and then repeat accordingly.

Here is some simplified example code: This works fine (but doesn't grab all rows, which varies, with the Date. It only grabs the first, hence the 'top 1')

select top 1 datewrk
from hours
where datewrk is not null and datewrk > '06/15/2004' and purchord = '4112'
order by datewrk

Soo, then this grabs all the rows with the Date, but doesn't 'skip' correctly. If you pick the date right before a valid row, as in there are rows of data for Date 6/18/2004 and you pick 6/17/2004 it will bring up the next date fine. BUT if you pick 6/15/2004 it will not 'skip ahead'. Any ideas? Thanks

select datewrk
from hours
where datewrk is not null and datewrk > '06/15/2004' and 1 = (case when Datewrk = (select min(Datewrk) from Hours where Datewrk is not null and Datewrk > '06/15/2004') then 1 else 0 end) and purchord = '4112'
order by datewrkDoes this work:SELECT datewrk
FROM hours
WHERE datewrk IS NOT NULL
AND datewrk > '06/15/2004'
AND purchord = '4112'
AND 1 = (case when Datewrk = (select min(Datewrk)
FROM Hours
WHERE Datewrk IS NOT NULL
AND purchord = '4112'
AND Datewrk > '06/15/2004') THEN 1 ELSE 0 END)
ORDER BY datewrk-PatP|||Yes, that works! THANK YOU.

Friday, March 23, 2012

Query using two column names in a table (to find rows near each other)

I have a table called Seats in my database...
CREATE TABLE [dbo].[Seats] (
[SeatSerialNo] [int] IDENTITY (1, 1) NOT NULL ,
[VehicleSerialNo] [int] NOT NULL ,
[RowNo] [smallint] NOT NULL ,
[ColumnNo] [smallint] NOT NULL ,
[SeatNo] [varchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO
This table defines the seats that are available for a given VehicleSerialNo
(the typical scenario would be a motor coach or possibly an aircraft). A
seat has a RowNo (how far down the vehicle it is), a ColumnNo (it's position
left to right on the vehicle) and a SeatNo (the actual seat number the
customer is given - e.g. please sit in seat number 40 - these can be numeric
or like aircraft seats numbers 23D etc).
I have another table called Passengers which stores the VehicleSerialNo (the
actual motor coach) and the SeatSerialNo (the seat they are sitting in on
that motor coach). Let's now assume this table contains lots of entries
already specifying where the existing passengers will be sitting.
Example: I now want to add 6 people on this vehicle and automatically
allocate each person a seat. I am trying to figure out whether this
automatic seat selection can be achieved in SQL Server or whether this
should be done on the client side using VB. Ideally you would always like
to make sure all 6 people are sitting on the same part of the motor coach
(unless it is getting full). Would it be possible to construct a query that
would select seats that are near each other based on RowNo and ColumnNo
(excluding SeatSerialNo's that exists in the Passengers table - e.g. no
double booking of a seat)? So I want to return a query that returns the 6
seats the system thinks are best. Can such a query be performed comparing
these column names (RowNo and ColumnNo) finding seats that are near to each
other.
Many thanks,
ChrisC-W
Its hard to suggest without seeing sample data+ relationship+ expected
result.
Why you don't have a primary on the table?
"C-W" <nomailplease@.microsoft.nospam> wrote in message
news:O0cKXJanFHA.3312@.tk2msftngp13.phx.gbl...
>I have a table called Seats in my database...
>
> CREATE TABLE [dbo].[Seats] (
> [SeatSerialNo] [int] IDENTITY (1, 1) NOT NULL ,
> [VehicleSerialNo] [int] NOT NULL ,
> [RowNo] [smallint] NOT NULL ,
> [ColumnNo] [smallint] NOT NULL ,
> [SeatNo] [varchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ) ON [PRIMARY]
> GO
>
> This table defines the seats that are available for a given
> VehicleSerialNo (the typical scenario would be a motor coach or possibly
> an aircraft). A seat has a RowNo (how far down the vehicle it is), a
> ColumnNo (it's position left to right on the vehicle) and a SeatNo (the
> actual seat number the customer is given - e.g. please sit in seat number
> 40 - these can be numeric or like aircraft seats numbers 23D etc).
>
> I have another table called Passengers which stores the VehicleSerialNo
> (the actual motor coach) and the SeatSerialNo (the seat they are sitting
> in on that motor coach). Let's now assume this table contains lots of
> entries already specifying where the existing passengers will be sitting.
>
> Example: I now want to add 6 people on this vehicle and automatically
> allocate each person a seat. I am trying to figure out whether this
> automatic seat selection can be achieved in SQL Server or whether this
> should be done on the client side using VB. Ideally you would always like
> to make sure all 6 people are sitting on the same part of the motor coach
> (unless it is getting full). Would it be possible to construct a query
> that would select seats that are near each other based on RowNo and
> ColumnNo (excluding SeatSerialNo's that exists in the Passengers table -
> e.g. no double booking of a seat)? So I want to return a query that
> returns the 6 seats the system thinks are best. Can such a query be
> performed comparing these column names (RowNo and ColumnNo) finding seats
> that are near to each other.
>
> Many thanks,
> Chris
>
>|||Sorry, that's just the way I scripted the table. SeatSerialNo is the
primary key.
I will try and work on some sample data.
"Uri Dimant" <urid@.iscar.co.il> wrote in message
news:uwOTGPanFHA.320@.TK2MSFTNGP09.phx.gbl...
> C-W
> Its hard to suggest without seeing sample data+ relationship+ expected
> result.
> Why you don't have a primary on the table?
>|||On Wed, 10 Aug 2005 12:54:59 +0100, C-W wrote:

>I have a table called Seats in my database...
>
>CREATE TABLE [dbo].[Seats] (
> [SeatSerialNo] [int] IDENTITY (1, 1) NOT NULL ,
> [VehicleSerialNo] [int] NOT NULL ,
> [RowNo] [smallint] NOT NULL ,
> [ColumnNo] [smallint] NOT NULL ,
> [SeatNo] [varchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ) ON [PRIMARY]
>GO
Hi Chris,
You have two good candidate keys in the table without the extra identity
column: (VehicleSerialNo, SeatNo) and (VehicleSerialNo, RowNo,
ColumnNo). My advice would be to drop the SeatSerialNo column, declare
one of the composite candidate keys to be the PRIMARY KEY (probably the
one with SeatNo, but it depends on a lot of factors I don't know) and
define a UNIQUE constraint for the other one.

>I have another table called Passengers which stores the VehicleSerialNo (th
e
>actual motor coach) and the SeatSerialNo (the seat they are sitting in on
>that motor coach).
That's redundant. What if a passenger has VehicleSerialNo 1 and
SeatSerialN0 17, but the row in Seats for SeatSerialNo says it's in
VehicleSerialNo 2?
If you keep SeatSerialNo in Seats and use it to refer to a seat in the
Passengers table, then remove VehicleSerialNo from the Passengers table
(the seat will always be in the same vehicle, regardless of who is
sitting on it). Or, if you drop SeatSerialNo from Seats, store the
combination of VehicleSerialNo and SeatNo in the Passengers table.
(snip)
>So I want to return a query that returns the 6
>seats the system thinks are best. Can such a query be performed comparing
>these column names (RowNo and ColumnNo) finding seats that are near to each
>other.
As Uri said. A repro script that others can run to recreate your test
data and the expected output would make it much easier to help you.
See www.aspfaq.com/5006 for more details and hints.
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Hugo,
Once i've generate the script to reproduce this I will explain the table
structure further (and hopefully will all make sense). I tried to reproduce
a simple example before but probably caused more confusion. The Seats table
does not actually contain the VehicleSerialNo. Hopefully all will make
sense when I post my script.
Thanks,
Chris
"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message
news:bg3kf15cvqe3r4k8hfo1jnr7uhpf52o3el@.
4ax.com...
> On Wed, 10 Aug 2005 12:54:59 +0100, C-W wrote:
>
> Hi Chris,
> You have two good candidate keys in the table without the extra identity
> column: (VehicleSerialNo, SeatNo) and (VehicleSerialNo, RowNo,
> ColumnNo). My advice would be to drop the SeatSerialNo column, declare
> one of the composite candidate keys to be the PRIMARY KEY (probably the
> one with SeatNo, but it depends on a lot of factors I don't know) and
> define a UNIQUE constraint for the other one.
>
> That's redundant. What if a passenger has VehicleSerialNo 1 and
> SeatSerialN0 17, but the row in Seats for SeatSerialNo says it's in
> VehicleSerialNo 2?
> If you keep SeatSerialNo in Seats and use it to refer to a seat in the
> Passengers table, then remove VehicleSerialNo from the Passengers table
> (the seat will always be in the same vehicle, regardless of who is
> sitting on it). Or, if you drop SeatSerialNo from Seats, store the
> combination of VehicleSerialNo and SeatNo in the Passengers table.
>
> (snip)
> As Uri said. A repro script that others can run to recreate your test
> data and the expected output would make it much easier to help you.
> See www.aspfaq.com/5006 for more details and hints.
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)

Query using dynamic column names

Hi All,
I have a table DATA with following 20 columns.
COL1, COL2, COL3, COL4,..... COL20
Another table TEMPLATE has one column COLNAME. The table contains 5 rows with the data COL2, COL5, COL6, COL9, COL12 in the column COLNAME.
Can someone help me to build sql statement to select data from DATA table for only columns listed in the TEMPLATE table. I want to do this using only one select statement. (I know how to do this with stored procedure but thats not what I want)
Also it is possible that row in TEMPLATE table may change.
Hope to get some positive replies.
Reagrds,
HK
If all the columns are of compatible types then you can do it like this:
CREATE TABLE Template (colname VARCHAR(10) PRIMARY KEY, ordinal_pos INTEGER
NOT NULL UNIQUE)
INSERT INTO Template VALUES ('COL1',1)
INSERT INTO Template VALUES ('COL2',2)
INSERT INTO Template VALUES ('COL3',3)
SELECT MIN(CASE
WHEN T.ordinal_pos = 1 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 1 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 1 AND T.colname='col3' THEN col3
/* .. etc */
END),
MIN(CASE
WHEN T.ordinal_pos = 2 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 2 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 2 AND T.colname='col3' THEN col3
END),
MIN(CASE
WHEN T.ordinal_pos = 3 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 3 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 3 AND T.colname='col3' THEN col3
END),
...
FROM Data AS D
CROSS JOIN Template AS T
GROUP BY D.col1, D.col2, D.col3, ... other cols
Otherwise use IF statements or dynamic SQL. You could also consider building
the SELECT statement client-side or retrieve all the columns but display
only the required ones to the user.
David Portas
SQL Server MVP
|||Thanks for your help David. But this will not work for me. The example I gave was to explain my problem. But in reality, I will not know all column names in the DATA table, only TEMPLATE table is the guide which has list of fields to select from DATA tabl
e.
Regards,
HK
"David Portas" wrote:

> If all the columns are of compatible types then you can do it like this:
> CREATE TABLE Template (colname VARCHAR(10) PRIMARY KEY, ordinal_pos INTEGER
> NOT NULL UNIQUE)
> INSERT INTO Template VALUES ('COL1',1)
> INSERT INTO Template VALUES ('COL2',2)
> INSERT INTO Template VALUES ('COL3',3)
> SELECT MIN(CASE
> WHEN T.ordinal_pos = 1 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 1 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 1 AND T.colname='col3' THEN col3
> /* .. etc */
> END),
> MIN(CASE
> WHEN T.ordinal_pos = 2 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 2 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 2 AND T.colname='col3' THEN col3
> END),
> MIN(CASE
> WHEN T.ordinal_pos = 3 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 3 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 3 AND T.colname='col3' THEN col3
> END),
> ...
> FROM Data AS D
> CROSS JOIN Template AS T
> GROUP BY D.col1, D.col2, D.col3, ... other cols
> Otherwise use IF statements or dynamic SQL. You could also consider building
> the SELECT statement client-side or retrieve all the columns but display
> only the required ones to the user.
> --
> David Portas
> SQL Server MVP
> --
>
>

Query using dynamic column names

Hi All,
I have a table DATA with following 20 columns.
COL1, COL2, COL3, COL4,..... COL20
Another table TEMPLATE has one column COLNAME. The table contains 5 rows wi
th the data COL2, COL5, COL6, COL9, COL12 in the column COLNAME.
Can someone help me to build sql statement to select data from DATA table fo
r only columns listed in the TEMPLATE table. I want to do this using only on
e select statement. (I know how to do this with stored procedure but thats n
ot what I want)
Also it is possible that row in TEMPLATE table may change.
Hope to get some positive replies.
Reagrds,
HKIf all the columns are of compatible types then you can do it like this:
CREATE TABLE Template (colname VARCHAR(10) PRIMARY KEY, ordinal_pos INTEGER
NOT NULL UNIQUE)
INSERT INTO Template VALUES ('COL1',1)
INSERT INTO Template VALUES ('COL2',2)
INSERT INTO Template VALUES ('COL3',3)
SELECT MIN(CASE
WHEN T.ordinal_pos = 1 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 1 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 1 AND T.colname='col3' THEN col3
/* .. etc */
END),
MIN(CASE
WHEN T.ordinal_pos = 2 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 2 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 2 AND T.colname='col3' THEN col3
END),
MIN(CASE
WHEN T.ordinal_pos = 3 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 3 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 3 AND T.colname='col3' THEN col3
END),
..
FROM Data AS D
CROSS JOIN Template AS T
GROUP BY D.col1, D.col2, D.col3, ... other cols
Otherwise use IF statements or dynamic SQL. You could also consider building
the SELECT statement client-side or retrieve all the columns but display
only the required ones to the user.
David Portas
SQL Server MVP
--|||Thanks for your help David. But this will not work for me. The example I gav
e was to explain my problem. But in reality, I will not know all column name
s in the DATA table, only TEMPLATE table is the guide which has list of fiel
ds to select from DATA tabl
e.
Regards,
HK
"David Portas" wrote:

> If all the columns are of compatible types then you can do it like this:
> CREATE TABLE Template (colname VARCHAR(10) PRIMARY KEY, ordinal_pos INTEGE
R
> NOT NULL UNIQUE)
> INSERT INTO Template VALUES ('COL1',1)
> INSERT INTO Template VALUES ('COL2',2)
> INSERT INTO Template VALUES ('COL3',3)
> SELECT MIN(CASE
> WHEN T.ordinal_pos = 1 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 1 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 1 AND T.colname='col3' THEN col3
> /* .. etc */
> END),
> MIN(CASE
> WHEN T.ordinal_pos = 2 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 2 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 2 AND T.colname='col3' THEN col3
> END),
> MIN(CASE
> WHEN T.ordinal_pos = 3 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 3 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 3 AND T.colname='col3' THEN col3
> END),
> ...
> FROM Data AS D
> CROSS JOIN Template AS T
> GROUP BY D.col1, D.col2, D.col3, ... other cols
> Otherwise use IF statements or dynamic SQL. You could also consider buildi
ng
> the SELECT statement client-side or retrieve all the columns but display
> only the required ones to the user.
> --
> David Portas
> SQL Server MVP
> --
>
>

Query using dynamic column names

Hi All,
I have a table DATA with following 20 columns.
COL1, COL2, COL3, COL4,..... COL20
Another table TEMPLATE has one column COLNAME. The table contains 5 rows with the data COL2, COL5, COL6, COL9, COL12 in the column COLNAME.
Can someone help me to build sql statement to select data from DATA table for only columns listed in the TEMPLATE table. I want to do this using only one select statement. (I know how to do this with stored procedure but thats not what I want)
Also it is possible that row in TEMPLATE table may change.
Hope to get some positive replies.
Reagrds,
HKIf all the columns are of compatible types then you can do it like this:
CREATE TABLE Template (colname VARCHAR(10) PRIMARY KEY, ordinal_pos INTEGER
NOT NULL UNIQUE)
INSERT INTO Template VALUES ('COL1',1)
INSERT INTO Template VALUES ('COL2',2)
INSERT INTO Template VALUES ('COL3',3)
SELECT MIN(CASE
WHEN T.ordinal_pos = 1 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 1 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 1 AND T.colname='col3' THEN col3
/* .. etc */
END),
MIN(CASE
WHEN T.ordinal_pos = 2 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 2 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 2 AND T.colname='col3' THEN col3
END),
MIN(CASE
WHEN T.ordinal_pos = 3 AND T.colname='col1' THEN col1
WHEN T.ordinal_pos = 3 AND T.colname='col2' THEN col2
WHEN T.ordinal_pos = 3 AND T.colname='col3' THEN col3
END),
...
FROM Data AS D
CROSS JOIN Template AS T
GROUP BY D.col1, D.col2, D.col3, ... other cols
Otherwise use IF statements or dynamic SQL. You could also consider building
the SELECT statement client-side or retrieve all the columns but display
only the required ones to the user.
--
David Portas
SQL Server MVP
--|||Thanks for your help David. But this will not work for me. The example I gave was to explain my problem. But in reality, I will not know all column names in the DATA table, only TEMPLATE table is the guide which has list of fields to select from DATA table.
Regards,
HK
"David Portas" wrote:
> If all the columns are of compatible types then you can do it like this:
> CREATE TABLE Template (colname VARCHAR(10) PRIMARY KEY, ordinal_pos INTEGER
> NOT NULL UNIQUE)
> INSERT INTO Template VALUES ('COL1',1)
> INSERT INTO Template VALUES ('COL2',2)
> INSERT INTO Template VALUES ('COL3',3)
> SELECT MIN(CASE
> WHEN T.ordinal_pos = 1 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 1 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 1 AND T.colname='col3' THEN col3
> /* .. etc */
> END),
> MIN(CASE
> WHEN T.ordinal_pos = 2 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 2 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 2 AND T.colname='col3' THEN col3
> END),
> MIN(CASE
> WHEN T.ordinal_pos = 3 AND T.colname='col1' THEN col1
> WHEN T.ordinal_pos = 3 AND T.colname='col2' THEN col2
> WHEN T.ordinal_pos = 3 AND T.colname='col3' THEN col3
> END),
> ...
> FROM Data AS D
> CROSS JOIN Template AS T
> GROUP BY D.col1, D.col2, D.col3, ... other cols
> Otherwise use IF statements or dynamic SQL. You could also consider building
> the SELECT statement client-side or retrieve all the columns but display
> only the required ones to the user.
> --
> David Portas
> SQL Server MVP
> --
>
>

Query using datetime datatype

hello,
so i have a table with column name Date with datetime as it's datatype. I'm
trying to run a select statement on it that will give me all rows where my
Date column has a datetime of 30 days or more. Can anyone help? I tried using
datediff but can't get it to work.
Thanks in advance!"FS" <FS@.discussions.microsoft.com> wrote in message
news:6A6874E0-38C5-4257-BA2A-4EEFF4D3A181@.microsoft.com...
> hello,
> so i have a table with column name Date with datetime as it's datatype.
> I'm
> trying to run a select statement on it that will give me all rows where my
> Date column has a datetime of 30 days or more. Can anyone help? I tried
> using
> datediff but can't get it to work.
> Thanks in advance!
WHERE dt <= DATEADD(DAY,-30,CURRENT_TIMESTAMP);
--
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--sql

Wednesday, March 21, 2012

Query to tranform rows to column

Hi

Your help for the following query will be highly apprecaited. I've
wasted alot of time on it. Data definition is at the bottom.

Thanks

-----------

Business need: User selects answers for few questions. Answers are
presented in the form of radio buttons.

Questions Table:

===================

QuestionID QuestionName

1 1.Rate your organization

2 10.Opportunity in your group

3 117.Effectiveness

------------

Answers Table:

==============

AnswerId AnswerName QuestionID

1 1.Best 1

2 2.Average 1

3 3.Wrose 1

4 1.Hardly Any 2

5 2.not too much 2

6 3.Average 2

7 4.Great Deal 2

8 1.Strong 3

9 2.Minor 3

10 3.Nothing 3

------------------

Lets say User ABC answered below:

For Question 1, she chose '2.Average'

For Question 2: she left blank

FOr Quesiton 3: she chose '2.Minor'

And for user XYZ:

For Question 1, she let blank

For Question 2: she left blank

FOr Quesiton 3: she chose '3.Nothing'

Then the Results table will look like this:

Results Table:

===============

Resultsid QuestionID AnswerId User

1 1 2 ABC

2 3 9 ABC

3 3 10 XYZ

----------------

Desired Output:

===============

User 1 10 117
-- -- -- --

ABC 2 2

XYZ 3

Explanation:

--> Show ALL distinct users on rows

--> show ALL distinct QuestionName on the columns BUT only display the
number before '.'

--> Show the chosen answer (answername) for each user but only display
the number before '.'

--------------------

if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[Questions]') and OBJECTPROPERTY(id, N'IsUserTable')
= 1)

drop table [dbo].[Questions]

GO

CREATE TABLE [dbo].[Questions] (

[QuestionId] [int] IDENTITY (1, 1) NOT NULL ,

[QuestionName] [nvarchar] (1000) COLLATE
SQL_Latin1_General_CP1_CI_AS NULL

) ON [PRIMARY]

GO

----------

if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[Answers]') and OBJECTPROPERTY(id, N'IsUserTable') =
1)

drop table [dbo].[Answers]

GO

CREATE TABLE [dbo].[Answers] (

[AnswerId] [int] IDENTITY (1, 1) NOT NULL ,

[AnswerName] [nvarchar] (150) COLLATE
SQL_Latin1_General_CP1_CI_AS NULL ,

[QuestionId] [int] NULL

) ON [PRIMARY]

GO

-----------

if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[Results]') and OBJECTPROPERTY(id, N'IsUserTable') =
1)

drop table [dbo].[Results]

GO

CREATE TABLE [dbo].[Results] (

[ResultId] [int] IDENTITY (1, 1) NOT NULL ,

[QuestionId] [int] NULL ,

[AnswerId] [int] NULL ,

[UserId] [nchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS
NULL

) ON [PRIMARY]

GO

--------------

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'1.Best' ,

1

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'2.Average' ,

1

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'3.Wrose' ,

1

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'1.Hardly Any' ,

2

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'2.not too much' ,

2

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'3.Average' ,

2

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'4.Great Deal' ,

2

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'1.Strong' ,

3

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'2.Minor' ,

3

)

go

INSERT Answers (

AnswerName ,

QuestionId

)

VALUES (

'3.Nothing' ,

3

)

go

----------

INSERT Questions (

QuestionName

)

VALUES (

'1.Rate your organization'

)

go

INSERT Questions (

QuestionName

)

VALUES (

'10.Opportunity in your group'

)

go

INSERT Questions (

QuestionName

)

VALUES (

'117.Effectiveness'

)

go

-----------

INSERT Results (

QuestionId ,

AnswerId ,

UserId

)

VALUES (

1 ,

2 ,

'ABC'

)

go

INSERT Results (

QuestionId ,

AnswerId ,

UserId

)

VALUES (

3 ,

9 ,

'ABC'

)

go

INSERT Results (

QuestionId ,

AnswerId ,

UserId

)

VALUES (

3 ,

10 ,

'XYZ'

)

goI could think of two ways of doing it:

select users.userid,
(select answerid from results where results.userid =
users.userid and questionid = 1) as answer1,
(select answerid from results where results.userid =
users.userid and questionid = 2) as answer2,
...
from (select distinct userid from results) as users
order by users.userid

or

select users.userid,
answer1.answerid as answer1,
answer2.answerid as answer2,
...
from (select distinct userid from results) as users
left outer join results answer1
on users.userid = answer1.userid
and answer1.answerid = 1
left outer join results answer2
on users.userid = answer2.userid
and answer1.answerid = 2
...
order by users.userid

--
David Rowland
Do you know what people are doing on your database server?
Find out with dbmonitor!
http://dbmonitor.tripod.com|||[posted and mailed, please reply in news]

(muzamil@.hotmail.com) writes:
> Your help for the following query will be highly apprecaited. I've
> wasted alot of time on it. Data definition is at the bottom.
>...
> Desired Output:
>===============
> User 1 10 117
> -- -- -- --
> ABC 2 2
> XYZ 3

SQL is not really well suited for type query, as the columns depend
on the data. You don't say so, but I assume that there can be
any number of questions. The usual recommendation for this sort of
crosstab queries is RAC, see http://www.rac4sql.net.

But since you provided scripts and tables, and everything else I usually
nag about, I felt compelled to provide a solution. This uses dynamic SQL.
For more information on dynamic SQL, see
http://www.sommarskog.se/dynamic_sql.html.

DECLARE @.selectlist varchar(8000),
@.selfjoin varchar(8000),
@.alias varchar(10),
@.elias varchar(10),
@.idstr varchar(10),
@.qnostr varchar(10)

-- Map id:s to the numbers before the dot.
CREATE TABLE #idmap(id int NOT NULL PRIMARY KEY,
qno smallint NOT NULL UNIQUE)

-- Help table to get all distinct users that appear.
CREATE TABLE #users (userid nchar(40) NOT NULL PRIMARY KEY)

-- Maps answers ids to numbers before the dot.
CREATE TABLE #answermap(id int NOT NULL PRIMARY KEY,
ansno smallint NOT NULL)

-- Fill Idmap
INSERT #idmap(id, qno)
SELECT QuestionId,
convert(smallint,
substring(QuestionName, 1, charindex('.', QuestionName) - 1))
FROM Questions

-- Fill answermap
INSERT #answermap(id, ansno)
SELECT AnswerId,
convert(smallint,
substring(AnswerName, 1, charindex('.', AnswerName) - 1))
FROM Answers

-- And get all users.
INSERT #users (userid)
SELECT DISTINCT UserId FROM Results

-- We now start to build a dynamic SQL statement. We build in two parts:
-- the SELECT list and the FROM clause.
SELECT @.selectlist = 'SELECT u.userid ',
@.selfjoin = 'FROM #users u '

-- We have to iterate of the #idmap table to build it. For the query
-- we need the id as a string, and the question number must be in [],
-- since it will be used as an identifier.
DECLARE build_cur INSENSITIVE CURSOR FOR
SELECT ltrim(str(id)), '[' + ltrim(str(qno)) + ']'
FROM #idmap
ORDER BY qno
OPEN build_cur

WHILE 1 = 1
BEGIN
FETCH build_cur INTO @.idstr, @.qnostr
IF @.@.fetch_status <> 0
BREAK

-- We will need two alias for the Results and #answermap table,
-- which will appear once for each question.
SELECT @.alias = 'a' + @.idstr, @.elias = 'e' + @.idstr

-- Add this question's answers to the SELECT list.
SELECT @.selectlist = @.selectlist + ', ' + @.qnostr + ' = ' +
@.elias + '.ansno '

-- And augment the FROM clause with this question. We left-join to
-- Results, since answer may be NULL. We need to look up answer in
-- the answer-map to get the real id.
SELECT @.selfjoin = @.selfjoin + char(10) +
'LEFT JOIN (Results ' + @.alias + ' JOIN #answermap ' + @.elias +
' ON ' + @.alias + '.AnswerId = ' + @.elias + '.id) ' +
' ON u.userid = ' + @.alias + '.UserId AND ' +
@.alias + '.QuestionId = ' + @.idstr
END
DEALLOCATE build_cur

-- Debug prints that show the actual query
PRINT @.selectlist
PRINT @.selfjoin

-- Run the beast!
EXEC (@.selectlist + @.selfjoin + ' ORDER BY u.userid')
go
DROP TABLE #users, #idmap, #answermap

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

query to split a database column ?

How can i write a query to split a database column and shows 2 new columns. In my database column

I have 2 mixing items and need to split out to 2 columns. Normally I have to write a query and change parameter

and run another query.

For example a database column with average number and range number.

Thanks

Daniel

Can you post some DDL, sample data and expected results?

AMB

|||

Hai,

Can you try the below query, and let me know that, it relates to your requirement or not:

DECLARE @.Columns varchar(1000)

SET @.Columns = ''

-- Create a temporary table.

CREATE TABLE #TempTable(Items varchar(50))

INSERT INTO #TempTable(Items) VALUES('A')

INSERT INTO #TempTable(Items) VALUES('A')

INSERT INTO #TempTable(Items) VALUES('A')

INSERT INTO #TempTable(Items) VALUES('B')

INSERT INTO #TempTable(Items) VALUES('B')

INSERT INTO #TempTable(Items) VALUES('B')

INSERT INTO #TempTable(Items) VALUES('C')

INSERT INTO #TempTable(Items) VALUES('C')

INSERT INTO #TempTable(Items) VALUES('D')

INSERT INTO #TempTable(Items) VALUES('D')

-- Before

SELECT * FROM #TempTable

-- Make a column list

SELECT

@.Columns = @.Columns + '[' + Items + '], '

FROM #TempTable

GROUP BY Items

-- Check the column values exits or not.

IF ( @.Columns IS NOT NULL ) AND ( @.Columns <> '' )

BEGIN

DECLARE @.Query nvarchar(1000)

SELECT @.Columns = SUBSTRING(@.Columns,1, LEN(@.Columns)-1)

SELECT @.Query = '

SELECT

*

FROM

(

SELECT

Items

FROM #TempTable

) AS Dummy

PIVOT

(

MAX(Items)

FOR Items IN (' + @.Columns + ')

)AS PvtTable'

EXEC(@.Query)

END

-- Drop the temporary table.

DROP TABLE #TempTable

Please clarify If I did any wrong.

Regards,

Kiran.Y

|||

Perhaps something like:

SET NOCOUNT ON

DECLARE @.MyTable table
( RowID int IDENTITY,
MyGroup int,
MyValue decimal(10,2)
)

INSERT INTO @.MyTable VALUES ( 1, 25 )
INSERT INTO @.MyTable VALUES ( 2, 5 )
INSERT INTO @.MyTable VALUES ( 1, 10 )
INSERT INTO @.MyTable VALUES ( 1, 15 )
INSERT INTO @.MyTable VALUES ( 1, 4 )
INSERT INTO @.MyTable VALUES ( 2, 6 )
INSERT INTO @.MyTable VALUES ( 2, 11 )
INSERT INTO @.MyTable VALUES ( 2, 0 )
INSERT INTO @.MyTable VALUES ( 1, 12 )

SELECT
Average = cast( avg( MyValue ) AS decimal(10,2)),
Range = ( cast( min( MyValue ) AS varchar(10)) + '-' +
cast( max( MyValue ) AS varchar(10)))
FROM @.MyTable
GROUP BY MyGroup

Average Range
13.20 4.00-25.00
5.50 0.00-11.00

|||

Hi Kiran

Thanks for answering my email. To clarify this below are my tables and columns and my query

Table: Item Stat_label Stat_value

column: Pack ID Stat_label_ID Stat_value_ID

Pack_Num Label ( has 2 rows Value

Ave and Range)

My query to list Pack_Num, Ave and it's value

SELECT Item.Pack_Num, Stat_label.Label, Stat_value.Value

FROM Item, Stat_label, Stat_value

WHERE Item.packID=Stat_label.Stat_label_ID AND

Stat_label.Stat_lavel_ID=Stat_value.Stat_value_ID

AND Stat_label.Label= Ave

My question: I want a query to list Pack_Num, Ave, Range and value

How can I do it?

That's mean this query need to split the Stat_label and list another

column name"Range".

Thanks
Daniel

|||

If you are using SQL 2005, look into the PIVOT function.

If you are using SQL 2000, explore using CASE.

Maybe these articles will help:

Pivot Tables -A simple way to perform crosstab operations
http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1131829,00.html

Pivot Tables - How to rotate a table in SQL Server
http://support.microsoft.com/default.aspx?scid=kb;en-us;175574

Pivot Tables -Dynamic Cross-Tabs
http://www.sqlteam.com/item.asp?ItemID=2955

Pivot Tables - Crosstab Pivot-table Workbench
http://www.simple-talk.com/sql/t-sql-programming/crosstab-pivot-table-workbench/

|||

Thanks all

I can not use "insert" because my account for this is read only and I avoid to list everything in a column and and use Excel pivot to summary.

Daniel

|||

Daniel,

If you would carefully examine the code provided, you will see that the INSERT statements are only building a sample table so that we could demonstrate a query suggestion.

You didn't bother to provide the table DDL, or sample data, so we have to waste our time creating sample data for you. and apparently, you can't read and understand example code.

|||

This may be closer to what you are hoping to find:

SELECT

i.Pack_Num,

sl.Stat_Label,
Average = cast( avg( sv.Stat_Value ) AS decimal(10,2)),
Range = ( cast( min( sv.Stat_Value ) AS varchar(10)) + '-' +
cast( max( sv.Stat_Value ) AS varchar(10)))
FROM Item i

JOIN Stat_Label sl

ON i.Pack_ID = sl.Stat_Label_ID

JOIN Stat_Value sv

ON sl.Stat_Label_ID = sv.Stat_Value_ID

WHERE sl.Label = 'Ave'
GROUP BY

i.Pack_Num,

sl.Stat_Label

|||

Thanks Anrnie but It is not working

Error at Average= cast......

Error at Range= (cast......

My Average and Range are decimal, no need cast

Do I have to declare a temp table?

Daniel

|||

Actually, it appears that the Stat_Value is most most likely a varchar().

Before we can help you any further, please post the table DDL and some sample data in the form of INSERT statements. Please refer to this link for help in preparing your material.

|||

Can SQL query create a new column or not?. DO NOT want to make a temp table.

Thanks

Daniel

|||

Can TSQL create a new column at the output?

If not I need 2 select statement but how to joint them? Can not use EXCEPT in TSQL? Tried to use UNION but

the results in one column.

It's complicated with creating a temp table since I do not know how to insert to temp table from database.

Thanks


Daniel

|||Please supply the requested information. (See my previous post.)

sql

Query to show column dependencies

I am trying to write a query to show column dependencies. I want to write a
query that will show me everything effected by changing a column in a table.
I want something where I can give it a table and column name and it will sho
w
me which tables/views and the columns that are dependent on that column I
want to change. I have been able to find the dependent columns, but I canno
t
tell which fields they are dependent upon. I also need it to show all
dependencies. For instance a column in table "A" is referenced in a column
view "X", then that column in view "X" is referenced in view "Y". Please
help!!! Here is the query I have so far.
----
--
declare @.tbl_nme as varchar(50)
declare @.col_nme as varchar(50)
set @.tbl_nme='V030_SCRMSCTM'
set @.col_nme= 'SCTM_SYS_DATE'
select
obj.name as obj_nm
, col.name as col_nm
, depobj.name as dep_obj_nm
, CASE depobj.type
WHEN 'C' THEN 'CHECK constraint'
WHEN 'D' THEN 'Default'
WHEN 'F' THEN 'FOREIGN KEY'
WHEN 'FN' THEN 'Scalar function'
WHEN 'IF' THEN 'In-lined table-function'
WHEN 'K' THEN 'PRIMARY KEY'
WHEN 'L' THEN 'Log'
WHEN 'P' THEN 'Stored procedure'
WHEN 'R' THEN 'Rule'
WHEN 'RF' THEN 'Replication filter stored procedure'
WHEN 'S' THEN 'System table'
WHEN 'TF' THEN 'Table function'
WHEN 'TR' THEN 'Trigger'
WHEN 'U' THEN 'User table'
WHEN 'V' THEN 'View'
WHEN 'X' THEN 'Extended stored procedure'
END as dep_obj_type
, null as dep_col_nm
from sysobjects obj
join syscolumns col on obj.id = col.id
left join (sysdepends dep join sysobjects depobj on depobj.id = dep.id)
on obj.id = dep.depid
and col.colid = dep.depnumber
where obj.name = @.tbl_nme
and col.name = @.col_nme
order by
obj.name,depobj.name, col_name(depid, dep.depnumber)
----
--
Jasontry this.. there is some problem with this clause...
col.colid = dep.depnumber
check it out.. anyways.. try this
declare @.tbl_nme as varchar(50)
declare @.col_nme as varchar(50)
declare @.level int
set @.level = 1
set @.tbl_nme='V030_SCRMSCTM'
set @.col_nme= 'SCTM_SYS_DATE'
select
obj.name as obj_nm
, col.name as col_nm
, depobj.name as dep_obj_nm
, CASE depobj.type
WHEN 'C' THEN 'CHECK constraint'
WHEN 'D' THEN 'Default'
WHEN 'F' THEN 'FOREIGN KEY'
WHEN 'FN' THEN 'Scalar function'
WHEN 'IF' THEN 'In-lined table-function'
WHEN 'K' THEN 'PRIMARY KEY'
WHEN 'L' THEN 'Log'
WHEN 'P' THEN 'Stored procedure'
WHEN 'R' THEN 'Rule'
WHEN 'RF' THEN 'Replication filter stored procedure'
WHEN 'S' THEN 'System table'
WHEN 'TF' THEN 'Table function'
WHEN 'TR' THEN 'Trigger'
WHEN 'U' THEN 'User table'
WHEN 'V' THEN 'View'
WHEN 'X' THEN 'Extended stored procedure'
END as dep_obj_type
, null as dep_col_nm
, @.level as level
into #temp
from sysobjects obj
join syscolumns col on obj.id = col.id
left join (sysdepends dep join sysobjects depobj on depobj.id = dep.id)
on obj.id = dep.depid
and col.colid = dep.depnumber
where obj.name = @.tbl_nme
and col.name = @.col_nme
while (@.@.rowcount > 0)
begin
set @.level = @.level + 1
insert into #temp
select
obj.name as obj_nm
, col.name as col_nm
, depobj.name as dep_obj_nm
, CASE depobj.type
WHEN 'C' THEN 'CHECK constraint'
WHEN 'D' THEN 'Default'
WHEN 'F' THEN 'FOREIGN KEY'
WHEN 'FN' THEN 'Scalar function'
WHEN 'IF' THEN 'In-lined table-function'
WHEN 'K' THEN 'PRIMARY KEY'
WHEN 'L' THEN 'Log'
WHEN 'P' THEN 'Stored procedure'
WHEN 'R' THEN 'Rule'
WHEN 'RF' THEN 'Replication filter stored procedure'
WHEN 'S' THEN 'System table'
WHEN 'TF' THEN 'Table function'
WHEN 'TR' THEN 'Trigger'
WHEN 'U' THEN 'User table'
WHEN 'V' THEN 'View'
WHEN 'X' THEN 'Extended stored procedure'
END as dep_obj_type
, null as dep_col_nm
, @.level as level
from sysobjects obj
join syscolumns col on obj.id = col.id
left join (sysdepends dep join sysobjects depobj on depobj.id = dep.id)
on obj.id = dep.depid
and col.colid = dep.depnumber
where exists(select 1 from #temp a where obj.name = a.dep_obj_nm and
col.name = a.dep_col_nm and level = @.level - 1 and dep_col_nm is not null)
end
select * from #temp
drop table #temp|||Sorry, I couldn't quite follow what you were trying to do here with the
'level' column. I still didn't see anything with the column names.
I think I am a little closer now with this, but it is still not quite right.
I am getting everything with this query, but it is linking it with every
column in the dependent table/view, not just the actual dependent columns.
========================================
=============
declare @.tbl_nme as varchar(50)
declare @.col_nme as varchar(50)
set @.tbl_nme='SCTM'
set @.col_nme= 'test_shop_dt_today'
select --distinct
obj.name as obj_nm
, col.name as col_nm
, depobj.name as dep_obj_nm
, CASE depobj.type
WHEN 'C' THEN 'CHECK constraint'
WHEN 'D' THEN 'Default'
WHEN 'F' THEN 'FOREIGN KEY'
WHEN 'FN' THEN 'Scalar function'
WHEN 'IF' THEN 'In-lined table-function'
WHEN 'K' THEN 'PRIMARY KEY'
WHEN 'L' THEN 'Log'
WHEN 'P' THEN 'Stored procedure'
WHEN 'R' THEN 'Rule'
WHEN 'RF' THEN 'Replication filter stored procedure'
WHEN 'S' THEN 'System table'
WHEN 'TF' THEN 'Table function'
WHEN 'TR' THEN 'Trigger'
WHEN 'U' THEN 'User table'
WHEN 'V' THEN 'View'
WHEN 'X' THEN 'Extended stored procedure'
END as dep_obj_type
, col_name(dep2.depid,dep2.depnumber) as dep_col_nm
from sysobjects obj
join syscolumns col on obj.id = col.id
left join (
(sysdepends dep join sysobjects depobj on depobj.id = dep.id)
join sysdepends dep2 on dep.id = dep2.depid
)
on obj.id = dep.depid
and col.colid = dep.depnumber
where obj.name = @.tbl_nme
and col.name = @.col_nme
========================================
=============
--
Jason
"Omnibuzz" wrote:

> try this.. there is some problem with this clause...
> col.colid = dep.depnumber
> check it out.. anyways.. try this
> declare @.tbl_nme as varchar(50)
> declare @.col_nme as varchar(50)
> declare @.level int
> set @.level = 1
> set @.tbl_nme='V030_SCRMSCTM'
> set @.col_nme= 'SCTM_SYS_DATE'
>
> select
> obj.name as obj_nm
> , col.name as col_nm
> , depobj.name as dep_obj_nm
> , CASE depobj.type
> WHEN 'C' THEN 'CHECK constraint'
> WHEN 'D' THEN 'Default'
> WHEN 'F' THEN 'FOREIGN KEY'
> WHEN 'FN' THEN 'Scalar function'
> WHEN 'IF' THEN 'In-lined table-function'
> WHEN 'K' THEN 'PRIMARY KEY'
> WHEN 'L' THEN 'Log'
> WHEN 'P' THEN 'Stored procedure'
> WHEN 'R' THEN 'Rule'
> WHEN 'RF' THEN 'Replication filter stored procedure'
> WHEN 'S' THEN 'System table'
> WHEN 'TF' THEN 'Table function'
> WHEN 'TR' THEN 'Trigger'
> WHEN 'U' THEN 'User table'
> WHEN 'V' THEN 'View'
> WHEN 'X' THEN 'Extended stored procedure'
> END as dep_obj_type
> , null as dep_col_nm
> , @.level as level
> into #temp
> from sysobjects obj
> join syscolumns col on obj.id = col.id
> left join (sysdepends dep join sysobjects depobj on depobj.id = dep.i
d)
> on obj.id = dep.depid
> and col.colid = dep.depnumber
> where obj.name = @.tbl_nme
> and col.name = @.col_nme
>
> while (@.@.rowcount > 0)
> begin
> set @.level = @.level + 1
> insert into #temp
> select
> obj.name as obj_nm
> , col.name as col_nm
> , depobj.name as dep_obj_nm
> , CASE depobj.type
> WHEN 'C' THEN 'CHECK constraint'
> WHEN 'D' THEN 'Default'
> WHEN 'F' THEN 'FOREIGN KEY'
> WHEN 'FN' THEN 'Scalar function'
> WHEN 'IF' THEN 'In-lined table-function'
> WHEN 'K' THEN 'PRIMARY KEY'
> WHEN 'L' THEN 'Log'
> WHEN 'P' THEN 'Stored procedure'
> WHEN 'R' THEN 'Rule'
> WHEN 'RF' THEN 'Replication filter stored procedure'
> WHEN 'S' THEN 'System table'
> WHEN 'TF' THEN 'Table function'
> WHEN 'TR' THEN 'Trigger'
> WHEN 'U' THEN 'User table'
> WHEN 'V' THEN 'View'
> WHEN 'X' THEN 'Extended stored procedure'
> END as dep_obj_type
> , null as dep_col_nm
> , @.level as level
> from sysobjects obj
> join syscolumns col on obj.id = col.id
> left join (sysdepends dep join sysobjects depobj on depobj.id = dep.i
d)
> on obj.id = dep.depid
> and col.colid = dep.depnumber
> where exists(select 1 from #temp a where obj.name = a.dep_obj_nm and
> col.name = a.dep_col_nm and level = @.level - 1 and dep_col_nm is not null)
> end
> select * from #temp
> drop table #temp
>|||What I had written will give you nested dependencies and shows you the level
it is nested with respect to the input table...
Ex: table 1 col1 --> view 1 col1 --> SP1
this will show that SP1 is also dependent on table1.. do I make sense?
I have modfied it..
check it and let me know if its fine..
declare @.tbl_nme as varchar(50)
declare @.col_nme as varchar(50)
declare @.level int
set @.level = 1
set @.tbl_nme='cpt56000'
set @.col_nme= 'o_crp'
select
obj.name as obj_nm
, col.name as col_nm
, depobj.name as dep_obj_nm
, CASE depobj.type
WHEN 'C' THEN 'CHECK constraint'
WHEN 'D' THEN 'Default'
WHEN 'F' THEN 'FOREIGN KEY'
WHEN 'FN' THEN 'Scalar function'
WHEN 'IF' THEN 'In-lined table-function'
WHEN 'K' THEN 'PRIMARY KEY'
WHEN 'L' THEN 'Log'
WHEN 'P' THEN 'Stored procedure'
WHEN 'R' THEN 'Rule'
WHEN 'RF' THEN 'Replication filter stored procedure'
WHEN 'S' THEN 'System table'
WHEN 'TF' THEN 'Table function'
WHEN 'TR' THEN 'Trigger'
WHEN 'U' THEN 'User table'
WHEN 'V' THEN 'View'
WHEN 'X' THEN 'Extended stored procedure'
END as dep_obj_type
, col_name(dep.depid,dep.depnumber) as dep_col_nm
, @.level as level
into #temp
from sysobjects obj
join syscolumns col on obj.id = col.id
left join (sysdepends dep join sysobjects depobj on depobj.id = dep.id)
on obj.id = dep.depid
and col.colid = dep.depnumber
where obj.name = @.tbl_nme
and col.name = @.col_nme
while (@.@.rowcount > 0)
begin
set @.level = @.level + 1
insert into #temp
select
obj.name as obj_nm
, col.name as col_nm
, depobj.name as dep_obj_nm
, CASE depobj.type
WHEN 'C' THEN 'CHECK constraint'
WHEN 'D' THEN 'Default'
WHEN 'F' THEN 'FOREIGN KEY'
WHEN 'FN' THEN 'Scalar function'
WHEN 'IF' THEN 'In-lined table-function'
WHEN 'K' THEN 'PRIMARY KEY'
WHEN 'L' THEN 'Log'
WHEN 'P' THEN 'Stored procedure'
WHEN 'R' THEN 'Rule'
WHEN 'RF' THEN 'Replication filter stored procedure'
WHEN 'S' THEN 'System table'
WHEN 'TF' THEN 'Table function'
WHEN 'TR' THEN 'Trigger'
WHEN 'U' THEN 'User table'
WHEN 'V' THEN 'View'
WHEN 'X' THEN 'Extended stored procedure'
END as dep_obj_type
, null as dep_col_nm
, @.level as level
from sysobjects obj
join syscolumns col on obj.id = col.id
left join (sysdepends dep join sysobjects depobj on depobj.id = dep.id)
on obj.id = dep.depid
and col.colid = dep.depnumber
where exists(select 1 from #temp a where obj.name = a.dep_obj_nm and
col.name = a.dep_col_nm and level = @.level - 1 and dep_col_nm is not null)
end
select * from #temp
drop table #temp|||It works except for the dep_col_nm field. It is giving the column name from
the source table, not the dependent table. That seems to be the show stoppe
r.
Thanks,
Jason
"Omnibuzz" wrote:

> What I had written will give you nested dependencies and shows you the lev
el
> it is nested with respect to the input table...
> Ex: table 1 col1 --> view 1 col1 --> SP1
> this will show that SP1 is also dependent on table1.. do I make sense?
> I have modfied it..
> check it and let me know if its fine..
>
> declare @.tbl_nme as varchar(50)
> declare @.col_nme as varchar(50)
> declare @.level int
> set @.level = 1
> set @.tbl_nme='cpt56000'
> set @.col_nme= 'o_crp'
>
> select
> obj.name as obj_nm
> , col.name as col_nm
> , depobj.name as dep_obj_nm
> , CASE depobj.type
> WHEN 'C' THEN 'CHECK constraint'
> WHEN 'D' THEN 'Default'
> WHEN 'F' THEN 'FOREIGN KEY'
> WHEN 'FN' THEN 'Scalar function'
> WHEN 'IF' THEN 'In-lined table-function'
> WHEN 'K' THEN 'PRIMARY KEY'
> WHEN 'L' THEN 'Log'
> WHEN 'P' THEN 'Stored procedure'
> WHEN 'R' THEN 'Rule'
> WHEN 'RF' THEN 'Replication filter stored procedure'
> WHEN 'S' THEN 'System table'
> WHEN 'TF' THEN 'Table function'
> WHEN 'TR' THEN 'Trigger'
> WHEN 'U' THEN 'User table'
> WHEN 'V' THEN 'View'
> WHEN 'X' THEN 'Extended stored procedure'
> END as dep_obj_type
> , col_name(dep.depid,dep.depnumber) as dep_col_nm
> , @.level as level
> into #temp
> from sysobjects obj
> join syscolumns col on obj.id = col.id
> left join (sysdepends dep join sysobjects depobj on depobj.id = dep.i
d)
> on obj.id = dep.depid
> and col.colid = dep.depnumber
> where obj.name = @.tbl_nme
> and col.name = @.col_nme
>
> while (@.@.rowcount > 0)
> begin
> set @.level = @.level + 1
> insert into #temp
> select
> obj.name as obj_nm
> , col.name as col_nm
> , depobj.name as dep_obj_nm
> , CASE depobj.type
> WHEN 'C' THEN 'CHECK constraint'
> WHEN 'D' THEN 'Default'
> WHEN 'F' THEN 'FOREIGN KEY'
> WHEN 'FN' THEN 'Scalar function'
> WHEN 'IF' THEN 'In-lined table-function'
> WHEN 'K' THEN 'PRIMARY KEY'
> WHEN 'L' THEN 'Log'
> WHEN 'P' THEN 'Stored procedure'
> WHEN 'R' THEN 'Rule'
> WHEN 'RF' THEN 'Replication filter stored procedure'
> WHEN 'S' THEN 'System table'
> WHEN 'TF' THEN 'Table function'
> WHEN 'TR' THEN 'Trigger'
> WHEN 'U' THEN 'User table'
> WHEN 'V' THEN 'View'
> WHEN 'X' THEN 'Extended stored procedure'
> END as dep_obj_type
> , null as dep_col_nm
> , @.level as level
> from sysobjects obj
> join syscolumns col on obj.id = col.id
> left join (sysdepends dep join sysobjects depobj on depobj.id = dep.i
d)
> on obj.id = dep.depid
> and col.colid = dep.depnumber
> where exists(select 1 from #temp a where obj.name = a.dep_obj_nm and
> col.name = a.dep_col_nm and level = @.level - 1 and dep_col_nm is not null)
> end
> select * from #temp
> drop table #temp
>|||Thats right. Thats why I said look into this statement
and col.colid = dep.depnumber
from my knowledge, depnumber gives the dependent procedure number..
will anyways look into it today.. we will find a solution for this :)
"JasonDWilson" wrote:
> It works except for the dep_col_nm field. It is giving the column name fr
om
> the source table, not the dependent table. That seems to be the show stop
per.
> Thanks,
> --
> Jason
>
> "Omnibuzz" wrote:
>|||Hi Jason,
I feel we cannot get the column level dependecy. To my knowledge, none
of the system tables has this information. The best we can get about
dependency is by using sp_depends for object level dependecy. Hope this help
s.

Query to sequentially number Null fields in a column

I'm trying to write a Query that will Update all the Null fields in Table1
column1 to 'P' and a 6 digit sequential number starting from 000001
including the leading zeros. Can someone help me figure out the correct
syntax? So far, nothing I've come up with is working right.
TIA
MattWell, if you don't want to add an IDENTITY column, and just want to add the
zero-padded char, you could:
1.) Create temp table with IDENTITY column and primary key from source table
1.) Generate identity values for all rows in target table in the temp table
2.) Update target table to include a zero-padded version of the identity
value
Example:
Let's say your table is called Customer and the primary key is CustomerKey
varchar(10)
BEGIN TRANSACTION
CREATE TABLE
#KeyGen
(
CustomerKey varchar(10) NOT NULL,
NewID int NOT NULL IDENTITY (1,1)
)
INSERT INTO KeyGen (CustomerKey) SELECT CustomerKey FROM Customer
WITH(TABLOCKX)
ALTER TABLE Customer ADD NewKey char(10) NOT NULL DEFAULT('')
UPDATE Customer SET NewKey = (SELECT RIGHT('000000' + CAST(NewID AS
varchar(6)), 6) FROM #KeyGen WHERE KeyGen.CustomerKey =
Customer.CustomerKey)
DROP TABLE #KeyGen
COMMIT TRANSACTION
Error handling is an exercise for the reader.
Cheers,
James Hokes
"Matt Williamson" <ih8spam@.spamsux.org> wrote in message
news:%23yx8L0oeGHA.4304@.TK2MSFTNGP05.phx.gbl...
> I'm trying to write a Query that will Update all the Null fields in Table1
> column1 to 'P' and a 6 digit sequential number starting from 000001
> including the leading zeros. Can someone help me figure out the correct
> syntax? So far, nothing I've come up with is working right.
> TIA
> Matt
>|||The problem is the source table doesn't have a primary key. That's what I'm
creating with this query.
I've been working with this code that I found in the archive, but I can't
get it to work
update temp_Reports tr1
set identifier_id = (select count(*) from temp_Reports tr2
where tr2.identifier_id <= tr1.identifier_id) + (select MAX(identifier_id)
FROM temp_Reports)
Where identifier_id is Null
I created this table as a temporary test
CREATE TABLE [temp_Reports] (
[identifier_id] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[somedata] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO
And added these values:
1 | Test1
2 | Test2
3 | Test3
Null | Test4
Null | Test5
I get
Server: Msg 170, Level 15, State 1, Line 1
Line 1: Incorrect syntax near 'tr1'.
Server: Msg 170, Level 15, State 1, Line 3
Line 3: Incorrect syntax near '+'.
but I'm not clear why.
Matt
"James Hokes" <noway@.nospamthanksanyway.com> wrote in message
news:eMW1O9oeGHA.3364@.TK2MSFTNGP05.phx.gbl...
> Well, if you don't want to add an IDENTITY column, and just want to add
> the zero-padded char, you could:
> 1.) Create temp table with IDENTITY column and primary key from source
> table
> 1.) Generate identity values for all rows in target table in the temp
> table
> 2.) Update target table to include a zero-padded version of the identity
> value
> Example:
> Let's say your table is called Customer and the primary key is CustomerKey
> varchar(10)
> BEGIN TRANSACTION
> CREATE TABLE
> #KeyGen
> (
> CustomerKey varchar(10) NOT NULL,
> NewID int NOT NULL IDENTITY (1,1)
> )
> INSERT INTO KeyGen (CustomerKey) SELECT CustomerKey FROM Customer
> WITH(TABLOCKX)
> ALTER TABLE Customer ADD NewKey char(10) NOT NULL DEFAULT('')
> UPDATE Customer SET NewKey = (SELECT RIGHT('000000' + CAST(NewID AS
> varchar(6)), 6) FROM #KeyGen WHERE KeyGen.CustomerKey =
> Customer.CustomerKey)
> DROP TABLE #KeyGen
> COMMIT TRANSACTION
>
> Error handling is an exercise for the reader.
> Cheers,
> James Hokes
> "Matt Williamson" <ih8spam@.spamsux.org> wrote in message
> news:%23yx8L0oeGHA.4304@.TK2MSFTNGP05.phx.gbl...
>|||>> The problem is the source table doesn't have a primary key. That's what
Make sure, in the future, to declare a primary key at the time of table
definition itself. Also, unless you have at least one set of columns that
are unique in the table, you have no way out.
The error is due to the alias used in the UPDATE clause. Moreover the logic
does not take into account the rows are already NULL. Assuming the second
column is unique within the table here is a workaround:
UPDATE tbl
SET col1 = ( SELECT COUNT( * )
FROM tbl t
WHERE t.col2 <= tbl.col2
AND t.col1 IS NULL )
+ ( SELECT MAX( col1 )
FROM tbl )
WHERE col1 IS NULL ;
Anith|||Matt,
1 -

> update temp_Reports tr1
Can not use alias in this way. Try:
update temp_Reports
set identifier_id = (select count(*) from temp_Reports tr2
where tr2.identifier_id <= temp_Reports.identifier_id) + (select
MAX(identifier_id)
FROM temp_Reports)
Where identifier_id is Null
go
2 -
The code will not give the result you are expecting, because the update runs
in a transaction, so the rows updated will not be seen by the "select"
statement that is doing the counting.
AMB
"Matt Williamson" wrote:

> The problem is the source table doesn't have a primary key. That's what I'
m
> creating with this query.
> I've been working with this code that I found in the archive, but I can't
> get it to work
> update temp_Reports tr1
> set identifier_id = (select count(*) from temp_Reports tr2
> where tr2.identifier_id <= tr1.identifier_id) + (select MAX(identifier_id)
> FROM temp_Reports)
> Where identifier_id is Null
> I created this table as a temporary test
> CREATE TABLE [temp_Reports] (
> [identifier_id] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [somedata] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ) ON [PRIMARY]
> GO
> And added these values:
> 1 | Test1
> 2 | Test2
> 3 | Test3
> Null | Test4
> Null | Test5
> I get
> Server: Msg 170, Level 15, State 1, Line 1
> Line 1: Incorrect syntax near 'tr1'.
> Server: Msg 170, Level 15, State 1, Line 3
> Line 3: Incorrect syntax near '+'.
> but I'm not clear why.
> Matt
> "James Hokes" <noway@.nospamthanksanyway.com> wrote in message
> news:eMW1O9oeGHA.3364@.TK2MSFTNGP05.phx.gbl...
>
>

Query to see if an int field starts with a certain number

How would I write a query on a table containing a column of ints, where I want to retrieve the rows where that int value starts with a number? I know that you can do this with strings by using "....WHERE thisfield LIKE ('123%')", but if 'thisfield' is an int, how would I do this? Thanks!Convert it to string, perform a substring, and then do your comparison.

Perhaps: substring(cast([thisfield] as varchar(50)),1,1)|||I don't know how the performance of this will compare, but if thisfield is non-negative, this should work as well:

[thisfield] / power(10, cast(log10([thisfield] as int))

Cheers,
-Isaac
|||

I hate to ask this, but the giant pink elephant in the room is "how do you have an int that doesn't start with a number?" What it sounds like you have is a column of string values that may or may not be an integer, and you want to see if the first character of the string is a number, right? For this it is:

thisColumn like '[1234567890]%'

But if the column is supposed to only contain integers, the best way to make sure that they are integers is to create the column using an integer datatype.