Showing posts with label write. Show all posts
Showing posts with label write. 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.

Monday, March 26, 2012

query where Case sensitive

hi, how to write query is Case sensitive?
select * from tb where fd like '%Temp'
will only return not "temp" ones? Thanks.Youcan explicitly define the collation for the query comparison:
select * from tb where fd like '%Temp' COLLATE
SQL_Latin1_General_CP1_CS_AS
CS which means "Case Sensitive"
HTH, jens Suessmeyer.|||Hi
Here are some examples
create table ABCD
(
courceid smallint not null,
description varchar(20) null
)
insert into ABCD(courceid,description)values (1,'DFh2AcZ')
insert into ABCD(courceid,description)values (2,'dHZ3')
)
SELECT description FROM ABCD where charindex(cast('H' as
varbinary(20)),cast(description as varbinary(20)))> 0
SELECT description
FROM ABCD
WHERE description ='dhZ3'COLLATE Latin1_General_BIN
SELECT description
FROM ABCD
WHERE charindex('h',description COLLATE Latin1_General_BIN)>0
--for sql2000
SELECT *
FROM Authors
WHERE au_lname COLLATE Latin1_General_CS_AS = 'green' COLLATE
Latin1_General_CS_AS
AND au_lname = 'green'
"js" <js@.someone.com> wrote in message
news:uxEv$ciNGHA.2920@.TK2MSFTNGP10.phx.gbl...
> hi, how to write query is Case sensitive?
> select * from tb where fd like '%Temp'
> will only return not "temp" ones? Thanks.
>

Wednesday, March 21, 2012

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 select data based on alphanumeric (surname) information.

Hello,

I am trying to write a query that will be able to select different segments of data based on spelling of the last name.

For example, in my database of name information, I need to select anyone whose last name starts with 'AAA' to 'EJJ'

then need to select anyone whose last name starts with 'EJK' to 'JAE' and so on...

I have tried using LIKE and some other methods with the > operator, but I can't get it to work. Does anyone have any suggestions or ideas on how to select data based on the alphanumeric characters this way?

Thanks

It isn't perfectly straightforward, particularly at the end of the ranges, but this will work...

create table person

(

lastName varchar(20)

)

insert into person

select 'AAA Dude'

union all

select 'Branson'

union all

select 'EJJ Dude'

union all

select 'Flighter'

union all

select 'Jaenor'

union all

select 'Zoinks'

--first

select *

from person

where lastName >= 'a' --Just one letter needed here because we want all

and lastName < 'EJK' --Added one letter to the range you want

lastName

--

AAA Dude

Branson

EJJ Dude

select *

from person

where lastName >= 'EJK'

and lastName < 'JAF' --again, one character more than the range

lastName

--

Flighter

Jaenor

select *

from person

where lastName >= 'JAF'

and lastName <= replicate('Z',20) --All zzz's would be the end of the range

--replicated to the max length of the column

lastName

--

Zoinks

|||

The following querry may fit for you,

Code Snippet

Create Table #person (

[lastName] Varchar(100)

);

Insert Into #person Values('AAA Dude');

Insert Into #person Values('Branson');

Insert Into #person Values('EJJ Dude');

Insert Into #person Values('Flighter');

Insert Into #person Values('Jaenor');

Insert Into #person Values('Zoinks');

Insert Into #person Values('EJK');

Insert Into #person Values('EJ');

Insert Into #person Values('EJJ');

Insert Into #person Values('EJJ ZZZZZZ');

Insert Into #person Values('JA');

Insert Into #person Values('JAE');

Select * from #person

Where

[lastName] >= 'AAA'

And [lastName] <= 'EJJ' + Replicate(Char(255),100) -- change the length with your datatype

Select * from #person

Where

[lastName] >= 'EJK'

And [lastName] <= 'JAE' + Replicate(Char(255),100) -- change the length with your datatype

|||

The reason I went with:

where lastName >= 'a' --Just one letter needed here because we want all

Was that I wanted to make sure that all alpha numeric values got in, even if the value 'A boinger' was in the table. If there are no spaces in the code value, it wouldn't matter. For example:

select case when 'a boinger' >= 'AAA' then 'yes' else 'no' end

Would be 'no' since 'a b' < 'AAA'

|||

Having worked with large criminal justice applications/databases, I've noticed that often when arrested, folks may have 'odd' street names, or the arresting officer is dealing with someone unconscious or intoxicated, so the name in the database may be '10 minute Fred', '2 Drink Limit', '1perp', '2ndDrunk', etc.

So, I would not limit names to starting with alpha...

('10 minute Fred' was never in a house/business for more than 10 minutes when he was burglurizing them.)

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.

Query to Search all fields in simple table

I am trying to write a simple search page that will searchall the fields in a database to find all records that match a user input string. The string could happen anywhere in any of the fields. I have a dataset and can write a query but am unsure what the format is for this simple task. I figured it would look like this:

SELECT Table.*

FROM Table

WHERE * = @.USERINPUT

But thats not working. Can someone help.? Thanks..

Not a simple task, but this should get you started.

SELECT *

FROM Table

WHERE field1 LIKE '%' + @.UserInput + '%' OR field2 LIKE'%'+@.UserInput+'%' OR...

sql

query to return only non null fields

Is it possible to write a query that returns only non null fields from a specified record? I have a big table with a record for each customer. the record contains a field for each item that can be purchased (only 6 items). I need to write an invoice but not every customer buys every product. I get the feeling Im going about this all wrong. Any help would be great

ThanksOriginally posted by nicky w
Is it possible to write a query that returns only non null fields from a specified record? I have a big table with a record for each customer. the record contains a field for each item that can be purchased (only 6 items). I need to write an invoice but not every customer buys every product. I get the feeling Im going about this all wrong. Any help would be great

Thanks
It would have been better to have the up to 6 items as up to 6 records in a separate table. No SQL query can return a variable number of columns, you would have to write some procedural code to run the query and then present the NOT NULL data.|||are you still in a designing stage? then you should change the design.
What if more items will be offered?

referential integrity will prevent "lost childs"

otherwise andrew is right. write some procedural code

Query to return latest record, multiple join fields

Hi
I need to write a query that returns the latest value(s) from a table,
'grouped' by the primary key (multiple fields), and the criteria to
derive the latest record is also based on multiple fields.
I have put together the DDL below as a simplified example, and want to
write a query that returns the following resultset:
company--project--value--
1 1 'fifth value'
1 2 '.2 fifth value'
2 1 '2 fifth value'
(KEY: company + project)
(LATEST RECORD: year + batch + item)
Thanks for any help
Sean
---
CREATE TABLE mytable (company INT, project INT, [year] int, batch int,
item int, value varchar(35))
INSERT INTO mytable VALUES (1, 1, 2003, 1, 1, 'first value')
INSERT INTO mytable VALUES (1, 1, 2003, 1, 2, 'second value')
INSERT INTO mytable VALUES (1, 1, 2003, 1, 3, 'third value')
INSERT INTO mytable VALUES (1, 1, 2003, 2, 1, 'fourth value')
INSERT INTO mytable VALUES (1, 1, 2003, 2, 2, 'fifth value')
INSERT INTO mytable VALUES (1, 1, 2002, 1, 1, 'sixth value')
INSERT INTO mytable VALUES (1, 1, 2002, 1, 2, 'seventh value')
INSERT INTO mytable VALUES (1, 1, 2002, 2, 1, 'eighth value')
INSERT INTO mytable VALUES (1, 2, 2003, 1, 1, '.2 first value')
INSERT INTO mytable VALUES (1, 2, 2003, 1, 2, '.2 second value')
INSERT INTO mytable VALUES (1, 2, 2003, 1, 3, '.2 third value')
INSERT INTO mytable VALUES (1, 2, 2003, 2, 1, '.2 fourth value')
INSERT INTO mytable VALUES (1, 2, 2003, 2, 2, '.2 fifth value')
INSERT INTO mytable VALUES (1, 2, 2002, 1, 1, '.2 sixth value')
INSERT INTO mytable VALUES (1, 2, 2002, 1, 2, '.2 seventh value')
INSERT INTO mytable VALUES (1, 2, 2002, 2, 1, '.2 eighth value')
INSERT INTO mytable VALUES (2, 1, 2003, 1, 1, '2 first value')
INSERT INTO mytable VALUES (2, 1, 2003, 1, 2, '2 second value')
INSERT INTO mytable VALUES (2, 1, 2003, 1, 3, '2 third value')
INSERT INTO mytable VALUES (2, 1, 2003, 2, 1, '2 fourth value')
INSERT INTO mytable VALUES (2, 1, 2003, 2, 2, '2 fifth value')
INSERT INTO mytable VALUES (2, 1, 2002, 1, 1, '2 sixth value')
INSERT INTO mytable VALUES (2, 1, 2002, 1, 2, '2 seventh value')
INSERT INTO mytable VALUES (2, 1, 2002, 2, 1, '2 eighth value')
---This table doesn't appear to have a primary key. I'll assume that the key is
supposed to be (company,project,year,batch,item). I've also assumed that the
batch and item numbers are in the range 0-999. If not, you'll have to amend
the YBI calculation accordingly.
SELECT T.company, T.project, T.value
FROM MyTable AS T
JOIN
(SELECT company, project,
MAX([year]*1000000+batch*1000+item) AS ybi
FROM Mytable
GROUP BY company, project) AS M
ON T.company = M.company
AND T.project = M.project
AND T.[year]*1000000+T.batch*1000+T.item = M.ybi
--
David Portas
--
Please reply only to the newsgroup
--sql

Saturday, February 25, 2012

Query Time and Network Traffic

I've got a pretty large db (150 gig -- 150mil records) and I've been struggling to write queries that run in a reasonable amount of time. Well, after doing everything I know to do (analyzing the queries, properly indexing fields, etc.) I've managed to get some pretty fast, efficient queries done. When I first took responsibility of the db, the queries I was writing were running in like 30 minutes. So, I've managed to cut them down to under a minute on average. That's all great, but I was messing around last night (when nobody else is at work...we have quite a large network) and all my apps using this db were running queries INSTANTLY. I mean REALLY fast! So, do you think it's safe to say that I've just done a really good job, and there isn't really any more I can do as far as query time when there is a lot of traffic on the network?

It never really occured to me that network traffic might slow down your queries. (Not that much anyway) Is this something anyone else has experienced before, or am I just crazy?As far as optimization of queries by applying indexing strategies, you probably exhausted your options. The next step will be to see if some denormalization can be introduced to minimize number of joins per query. Of course all this is only if users are not returning the world back. You're absolutely right when suspecting the network traffic. It's especially true when large resultsets are floating around.|||Network traffic won't slow down SQL Server's processing of your queries, but it will definitley slow down the return of large result sets.

But low network traffic is probably not the only factor affecting the speed of your queries after-hours. It is also likely that there were few if any other users accessing your database tables and locking resources for inserts, updates, and deletes. If your database where you are running these queries (they sound like OLAP queries) is also used for transaction processing, then these two functionalities my frequently fight for resources. Consider creating a copy of your database (use replication to keep it synchronized) and thus split the processing load between two servers.

blindman

Monday, February 20, 2012

Query syntax help

I am trying to write a query that returns all suppliers within a given range
that either do not have any insurance (appear only in Suppliers table) or
Suppliers where the insurance has expired from a given date
Eg 4 Suppliers
Supplier1 - no insurance
Supplier2 - insurance expired
Supplier3 - insurance current
Supplier4 - not in range
The Supplier range is 'where AccRef like '^SC%'
The Expiry Date is less than or equal to '20071130'
The result set would include Supplier1 because it is not in the
InsuranceDetails table at all and Supplier2 because the insurance has
expired.
How can I do this in one query?
I have included some SQL for your info
Thanks
A
CREATE TABLE [dbo].[Suppliers](
[AccRef] [nvarchar](8) NOT NULL,
[AccName] [nvarchar](30) NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[InsuranceDetails](
[AccRef] [nvarchar](8) NOT NULL,
[DateExpire] [datetime] NOT NULL
) ON [PRIMARY]
INSERT INTO dbo.Suppliers ([AccRef], [AccName])
SELECT '^SC100' As Expr1, 'Supplier1' as Expr2
INSERT INTO dbo.Suppliers ([AccRef], [AccName])
SELECT '^SC200' AS Expr1, 'Supplier2' as Expr2
INSERT INTO dbo.Suppliers ([AccRef], [AccName])
SELECT '^SC300' AS Expr1, 'Supplier3' as Expr2
INSERT INTO dbo.Suppliers ([AccRef], [AccName])
SELECT '10000' AS Expr1, 'Supplier4' as Expr2
INSERT INTO dbo.InsuranceDetails ([AccRef], [DateExpire])SELECT '^SC300' AS
Expr1, '20080331' as Expr2
INSERT INTO dbo.InsuranceDetails ([AccRef], [DateExpire])SELECT '^SC200' AS
Expr1, '20071101' as Expr2
There are a variety of ways you can do this. Here is one:
SELECT s1.accref, s1.AccName
FROM suppliers s1
WHERE s1.accref LIKE '^SC%'
AND COALESCE(
( SELECT i1.dateexpire
FROM InsuranceDetails i1
WHERE i1.accref = s1.accref ), '19000101' )
<= '20071130' ;
Anith