Showing posts with label below. Show all posts
Showing posts with label below. Show all posts

Friday, March 30, 2012

Help with SQL Query

Given the following two tables below, I need help in writing a query that would retreive only 3 or less distinct values of BDesc from tbB table for every row found in tbA.

for example:

I expect result to be:

Aid Bdesc
100 1st Desc for 100
100 2nd Desc for 100
100 3rd Desc for 100
200 1st Desc for 200
200 2nd Desc for 200
200 3rd Desc for 200
300 1st Desc for 300
300 2nd Desc for 300
300 3rd Desc for 300
400 1st Desc for 400
500 1st Desc for 500
500 3rd Desc for 500

The tables are:

use tempdb

go

set nocount on

if exists (select name from sysobjects where name = 'TbA')

Drop table TbA

Create Table TbA ( Aid int )

Insert into TbA values(100)

Insert into TbA values(200)

Insert into TbA values(300)

Insert into TbA values(400)

--select * from TbA

if exists (select name from sysobjects where name = 'TbB')

Drop table TbB

Create Table TbB ( Bid int , BDesc varchar(50) )

INSERT INTO TbB Values(100, '1st Desc for 100')

INSERT INTO TbB Values(100, '2nd Desc for 100')

INSERT INTO TbB Values(100, '3rd Desc for 100')

INSERT INTO TbB Values(100, '3rd Desc for 100')

INSERT INTO TbB Values(200, '1st Desc for 200')

INSERT INTO TbB Values(200, '2nd Desc for 200')

INSERT INTO TbB Values(200, '3rd Desc for 200')

INSERT INTO TbB Values(200, '4th Desc for 200')

INSERT INTO TbB Values(200, '1st Desc for 200')

INSERT INTO TbB Values(300, '1st Desc for 300')

INSERT INTO TbB Values(300, '2nd Desc for 300')

INSERT INTO TbB Values(300, '3rd Desc for 300')

INSERT INTO TbB Values(300, '4th Desc for 300')

INSERT INTO TbB Values(400, '1st Desc for 400')

INSERT INTO TbB Values(400, '1st Desc for 400')

INSERT INTO TbB Values(500, '1st Desc for 500')

INSERT INTO TbB Values(500, '1st Desc for 500')

INSERT INTO TbB Values(500, '3rd Desc for 500')

--select * from TbB

Thanks for your help with this...

Here ya go

Code Snippet

selectdistinct TbB.*

from(selectdistinct aid from TbA)as TbA

innerjoin TbB

on TbA.Aid = TbB.Bid

and TbB.BDesc in

(selectdistincttop 3 BDesc from TbB where Bid = TbA.Aid orderby BDesc)

|||Thanks|||

How about if I wanted to get the result like this:

ColA ColB

100 1st Descfor 100, 2nd Descfor 100, 3rd Descfor 100

200 1st Descfor 200, 2nd Descfor 200, 3rd Descfor 200

300 1st Descfor 300, 2nd Descfor 300, 3rd Descfor 300

400 1st Descfor 400

500 1st Descfor 500, 3rd Descfor 500

|||hi, you can try using a udf

CREATE FUNCTION dbo.GetBDesc
(
@.AID int
)
RETURNS varchar(800)
AS
BEGIN
DECLARE @.BDesc varchar(100)
SET @.BDesc = ''
SELECT
@.BDesc = @.BDesc + BDesc + ','
FROM (SELECT DISTINCT TOP 3 * FROM TbB a WHERE a.BID = @.AID) b
WHERE BID = @.AID
ORDER BY
BDesc

IF @.BDesc <> '' SET @.BDesc = LEFT(@.BDesc, LEN(@.BDesc) - 1)

RETURN @.BDesc

END

GO

select *
, dbo.GetBDesc(AID)
from tba|||

If you use SQL Server 2005 you dont need a function...

Here the sample,

Code Snippet

Create Table #TableA(

Aid int );

Insert into #TableA values(100)

Insert into #TableA values(200)

Insert into #TableA values(300)

Insert into #TableA values(400)

Insert into #TableA values(500)

Create Table #TableB(

Bid int

,BDesc varchar(50)

)

INSERT INTO #TableB Values(100, '1st Desc for 100')

INSERT INTO #TableB Values(100, '2nd Desc for 100')

INSERT INTO #TableB Values(100, '3rd Desc for 100')

INSERT INTO #TableB Values(100, '3rd Desc for 100')

INSERT INTO #TableB Values(200, '1st Desc for 200')

INSERT INTO #TableB Values(200, '2nd Desc for 200')

INSERT INTO #TableB Values(200, '3rd Desc for 200')

INSERT INTO #TableB Values(200, '4th Desc for 200')

INSERT INTO #TableB Values(200, '1st Desc for 200')

INSERT INTO #TableB Values(300, '1st Desc for 300')

INSERT INTO #TableB Values(300, '2nd Desc for 300')

INSERT INTO #TableB Values(300, '3rd Desc for 300')

INSERT INTO #TableB Values(300, '4th Desc for 300')

INSERT INTO #TableB Values(400, '1st Desc for 400')

INSERT INTO #TableB Values(400, '1st Desc for 400')

INSERT INTO #TableB Values(500, '1st Desc for 500')

INSERT INTO #TableB Values(500, '1st Desc for 500')

INSERT INTO #TableB Values(500, '3rd Desc for 500')

;With DistinctData

as

(

Select Distinct A.Aid,B.BDesc from #TableA A Join #TableB B On A.Aid =B.Bid

),

RowData

as

(

Select Aid,Bdesc,Row_Number() Over(Partition By Aid Order By BDesc) RowID From DistinctData

)

/*

Select

Aid,

BDesc

From

RowData

Where

RowID <=3

*/

Select Distinct

Aid

,Substring((Select ',' + BDesc as [text()] From RowData Sub Where Sub.Aid=Main.Aid And Sub.RowId<=3 For XML Path(''), Elements),2,8000) as Descs

From

RowData Main

|||MG,

How about these two queries (both require SQL 2005)

select a.aid, b.bdesc
from tbA a
cross apply
(select distinct top (3) bdesc from tbB b where b.bid = a.aid) b
;

select a.aid as ColA, stuff((select distinct top (3) ', ' + bdesc from tbB b where b.bid = a.aid order by 1 for xml path('')),1,2,'') as ColB
from tbA a
;

The second one puts them into a single column for you.

Rob|||I should have mentioned that this is for SQL 2000 and for an OLTP environment. The procedure processes approx. 20,000 rows and right now it's using cursor logic which is slowing things down, so I was looking for ways to use set based processing. The function idea is good, but again its going to be row by row processing.|||

The function approach should be a significant improvement over any cursor processing.

Is there something we're not understanding about what you want to accomplish?

|||

Hi Rhamille Golimlim,

There is an issue when using "order by" during an aggregate concatenation query.

PRB: Execution Plan and Results of Aggregate Concatenation Queries Depend Upon Expression Location

http://support.microsoft.com/default.aspx/kb/287515

AMB

|||thanks for the tip hunchback. would it still show a different execution plan if we put the order by inside the subquery?|||

Hi Rhamille Golimlim,

If you put the "order by" clause inside the derived table, then how are you going to be sure that the result is sorted if the only way to asure a sorted resultset is using the "order by" clause in the statement that pull the data?. It is like sorting inside a view and not using "order by" clause when you pull from the view.

Concatenating row values in T-SQL

http://www.projectdmx.com/tsql/rowconcatenate.aspx

AMB

|||hi hunchback,

cool, would the xml path approach be the best work around for this scenario? or are there other alternatives or tsql hacks?

/rhamille

help with SQL procedure conversion

Hi Guys, I need some in SQL conversion from Oracle to SQL Server...Here is the procedure in T-SQL..When I run the below SQL in SQL Server, it is going in infinite loop. When I click stop, I am getting the error ......
"Invalid length parameter passed to the substring function."
at the following line
SELECT @.RoleID_in = CONVERT(NUMERIC(8, 2), SUBSTRING(@.UserRoles_in, 1, CHARINDEX(',', @.UserRoles_in) - 1))
----
DECLARE @.objid_in INT
DECLARE @.objclass_in INT
DECLARE @.userid_in INT
DECLARE @.userRoles_in VARCHAR(3000)
DECLARE @.RoleID_in INT
DECLARE @.cnt INT

DECLARE csr CURSOR FOR
SELECT * FROM objectACL
OPEN csr
WHILE (0 = 0)
BEGIN --(

fetch NEXT FROM csr INTO @.objid_in, @.objclass_in, @.userid_in, @.userRoles_in
IF (@.@.FETCH_STATUS = -1)
BREAK
SELECT @.UserRoles_in = SUBSTRING(@.UserRoles_in, 2, LEN(@.UserRoles_in))
WHILE (0 = 0)
BEGIN --(
SELECT @.RoleID_in = CONVERT(NUMERIC(8, 2), SUBSTRING(@.UserRoles_in, 1, CHARINDEX(',', @.UserRoles_in) - 1))
SELECT @.cnt = COUNT(*) FROM nodetable WHERE objtype = 21 AND id = @.RoleId_in
IF ( @.cnt = 0 )
BEGIN
INSERT INTO error_report VALUES( 'ObjectACL' , '0' , 'UserRoles refering to Non-existing Role : ' + CAST(@.RoleID_in AS VARCHAR) )
END
SELECT @.UserRoles_in = SUBSTRING(@.UserRoles_in, LEN(@.RoleID_in) + 2, LEN(@.UserRoles_in))
IF ( @.UserRoles_in is null )
BEGIN
BREAK
END
END --)
END --)
close csr
DEALLOCATE csr
GO
------

Corresponding procedure in Oracle
-----
declare
cursor csr is select * from objectACL;

objid_in number;
objclass_in number;
userid_in number;
userRoles_in varchar2(3000);
RoleID_in number;
cnt number;

begin
open csr;
loop
fetch csr into objid_in, objclass_in, userid_in, userRoles_in;
exit when csr%notfound;

UserRoles_in := substr(UserRoles_in, 2);

loop
RoleID_in := to_number(substr(UserRoles_in, 1, instr(UserRoles_in, ',')-1));
select count(1) into cnt from nodetable where objtype=21 and id=RoleId_in;
if (cnt =0) then
insert into error_report values ('ObjectACL', '0', 'UserRoles refering to Non-existing Role : '||RoleId_in);
end if;

UserRoles_in := substr(userRoles_in, length(RoleId_in)+2);

if (userRoles_in is null) then
exit;
end if;
end loop;
end loop;
close csr;
end;
/
------Dear Lord, PSQL is a sucky language. That is pretty near unreadable.

Do yourself a favor and don't even try to convert this into TSQL directly. Oracle developers love cursors, but set-based operations are almost always easier to debug and run faster. I'd better dollars to doughnut holes you don't even need a cursor for this.

Post your table layout and a description of what you are trying to do.

Monday, March 26, 2012

Help with SP syntax

I have the stored proc. below and I'm passing two
parameters. What I'm trying to do is if either one of
the parameters is equal to "All", then change the value
of the paramter to an empty string or set another
variable to an empty string. SQL doesn't like the code I
have below. Please help.
CREATE PROCEDURE GetUSFSUsers
(
@.Role nvarchar(100),
@.Unit nvarchar(20)
)
AS
Declare @.Role2 nvarchar(100)
Declare @.Unit2 nvarchar(20)
If @.Role = 'All'
@.Role2 = ''
Else
@.Role2 = @.Role
If @.Unit = 'All'
@.Unit2 = ''
Else
@.Unit2 = @.UnitYou can change it to
if @.role = 'all'
set @.role2 = ''
else
set @.role2 = @.role
if @.unit = 'all'
set @.unit2 = ''
else
set @.unit2 = @.unit
HTH
Ray Higdon MCSE, MCDBA, CCNA
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Friday, March 23, 2012

Help with sequel statement please. Thanks.

Sorry for dup. Please ignore the previous one. Thanks.
Hi all,
How can I return the results below. Any help would greatly appreciate. The
business rule is show below.
IF OBJECT_ID('Tempdb.dbo.#Policy_nb', 'u') IS NOT NULL
DROP TABLE #Policy_nb
GO
CREATE TABLE #Policy_nb
(
Policy_Id INT NULL,
CurrAgent_id INT NULL,
UploadTp_id INT NULL
)
GO
INSERT #Policy_nb (Policy_Id, CurrAgent_id, UploadTp_id) VALUES (382099,
4894, 3)
INSERT #Policy_nb (Policy_Id, CurrAgent_id, UploadTp_id) VALUES (374943,
614, 3)
INSERT #Policy_nb (Policy_Id, CurrAgent_id, UploadTp_id) VALUES (376279,
4710, 2)
GO
IF OBJECT_ID('Tempdb.dbo.#HuonUpload_nb', 'u') IS NOT NULL
DROP TABLE #HuonUpload_nb
GO
CREATE TABLE #HuonUpload_nb
(
Policy_id INT NULL,
UploadTp_Id INT NULL,
UploadStatus_dt DATETIME NULL
)
GO
INSERT #HuonUpload_nb VALUES (382099, 3, '10/03/2005 11:27AM')
INSERT #HuonUpload_nb VALUES (382099, 2, '10/03/2005 11:25AM')
INSERT #HuonUpload_nb VALUES (382099, 1, '10/03/2005 11:21AM')
INSERT #HuonUpload_nb VALUES (382099, 4, '09/30/2005 9:24AM')
INSERT #HuonUpload_nb VALUES (382099, 1, '09/30/2005 9:22AM')
INSERT #HuonUpload_nb VALUES (382099, 2, '09/30/2005 9:21AM')
INSERT #HuonUpload_nb VALUES (382099, 2, '09/30/2005 9:12AM')
INSERT #HuonUpload_nb VALUES (382099, 1, '09/29/2005 11:36PM')
INSERT #HuonUpload_nb VALUES (382099, 4, '09/29/2005 09:45AM')
INSERT #HuonUpload_nb VALUES (382099, 2, '09/28/2005 01:18PM')
INSERT #HuonUpload_nb VALUES (374943, 3, '10/03/2005 11:26AM')
INSERT #HuonUpload_nb VALUES (374943, 2, '10/03/2005 10:20AM')
INSERT #HuonUpload_nb VALUES (374943, 1, '10/03/2005 10:15AM')
INSERT #HuonUpload_nb VALUES (376279, 1, '09/13/2005 2:19PM')
INSERT #HuonUpload_nb VALUES (376279, 2, '09/13/2005 2:36PM')
go
SELECT *
FROM #Policy_nb
GO
Policy_Id CurrAgent_id UploadTp_id
-- -- --
382099 4894 3
374943 614 3
376279 4710 2
SELECT *
FROM #HuonUpload_nb
GO
Policy_id UploadTp_Id UploadStatus_dt
-- -- --
382099 3 2005-10-03 11:27:00.000
382099 2 2005-10-03 11:25:00.000
382099 1 2005-10-03 11:21:00.000
382099 4 2005-09-30 09:24:00.000
382099 1 2005-09-30 09:22:00.000
382099 2 2005-09-30 09:21:00.000
382099 2 2005-09-30 09:12:00.000
382099 1 2005-09-29 23:36:00.000
382099 4 2005-09-29 09:45:00.000
382099 2 2005-09-28 13:18:00.000
374943 3 2005-10-03 11:26:00.000
374943 2 2005-10-03 10:20:00.000
374943 1 2005-10-03 10:15:00.000
376279 1 2005-09-13 14:19:00.000
376279 2 2005-09-13 14:36:00.000
-- Rules: Return only these rows which has UploadTp_id = 1, 2 and 3.
--Testing... Not working...
SELECT a.CurrAgent_id,
b.Policy_id,
b.UploadTp_Id,
b.UploadStatus_dt
FROM #Policy_nb AS a
JOIN #HuonUpload_nb AS b
ON a.Policy_id = b.Policy_id
JOIN (SELECT TOP 100 PERCENT Policy_id, UploadTp_id,
MAX(UploadStatus_dt) AS 'UploadStatus_dt'
FROM #HuonUpload_nb
WHERE UploadTp_id IN (1, 2, 3)
GROUP BY Policy_id, UploadTp_id
ORDER BY Policy_id ASC, UploadStatus_dt DESC) AS c
ON c.Policy_id = b.Policy_id
AND c.UploadTp_id = b.UploadTp_id
AND c.UploadStatus_dt = b.UploadStatus_dt
ORDER BY b.Policy_id DESC, b.UploadStatus_dt DESC
GO
--Result want:
CurrAgent_id Policy_id UploadTp_Id UploadStatus_dt
-- -- -- --
4894 382099 3 2005-10-03 11:27:00.000
4894 382099 2 2005-10-03 11:25:00.000
4894 382099 1 2005-10-03 11:21:00.000
614 374943 3 2005-10-03 11:26:00.000
614 374943 2 2005-10-03 10:20:00.000
614 374943 1 2005-10-03 10:15:00.000There is no duplicate (unless you mean your post from 8/29).
Please consider using a newsreader, which doesn't have as many
synchronization issues as the web-based interfaces.
http://www.aspfaq.com/5007|||Try this,
SELECT p.CurrAgent_id, h.Policy_id, h.UploadTp_Id, max(h.UploadStatus_dt) AS
UploadStatus_dt
FROM HuonUpload_nb h inner join Policy_nb p on h.policy_id = p.policy_id
WHERE h.UploadTp_Id <=3 AND p.CurrAgent_id IN
(SELECT currAgent_id
FROM (SELECT PN.currAgent_id
FROM HuonUpload_nb NB INNER JOIN POLICY_NB PN ON NB.policy_ID =
PN.policy_ID
WHERE (nb.UploadTp_Id <=3)
GROUP BY pn.currAgent_id, nb.Policy_id, nb.UploadTp_id) AS X
GROUP BY currAgent_id
HAVING count(currAgent_id) = 3)
GROUP BY p.CurrAgent_id, h.Policy_id, h.UploadTp_Id
ORDER BY h.Policy_id DESC, h.UploadTP_Id DESC
Note: # were removed
Regards,
David
"Lam Nguyen" wrote:

> Sorry for dup. Please ignore the previous one. Thanks.
> Hi all,
> How can I return the results below. Any help would greatly appreciate. T
he
> business rule is show below.
>
> IF OBJECT_ID('Tempdb.dbo.#Policy_nb', 'u') IS NOT NULL
> DROP TABLE #Policy_nb
> GO
> CREATE TABLE #Policy_nb
> (
> Policy_Id INT NULL,
> CurrAgent_id INT NULL,
> UploadTp_id INT NULL
> )
> GO
> INSERT #Policy_nb (Policy_Id, CurrAgent_id, UploadTp_id) VALUES (382099,
> 4894, 3)
> INSERT #Policy_nb (Policy_Id, CurrAgent_id, UploadTp_id) VALUES (374943,
> 614, 3)
> INSERT #Policy_nb (Policy_Id, CurrAgent_id, UploadTp_id) VALUES (376279,
> 4710, 2)
> GO
> IF OBJECT_ID('Tempdb.dbo.#HuonUpload_nb', 'u') IS NOT NULL
> DROP TABLE #HuonUpload_nb
> GO
> CREATE TABLE #HuonUpload_nb
> (
> Policy_id INT NULL,
> UploadTp_Id INT NULL,
> UploadStatus_dt DATETIME NULL
> )
> GO
> INSERT #HuonUpload_nb VALUES (382099, 3, '10/03/2005 11:27AM')
> INSERT #HuonUpload_nb VALUES (382099, 2, '10/03/2005 11:25AM')
> INSERT #HuonUpload_nb VALUES (382099, 1, '10/03/2005 11:21AM')
> INSERT #HuonUpload_nb VALUES (382099, 4, '09/30/2005 9:24AM')
> INSERT #HuonUpload_nb VALUES (382099, 1, '09/30/2005 9:22AM')
> INSERT #HuonUpload_nb VALUES (382099, 2, '09/30/2005 9:21AM')
> INSERT #HuonUpload_nb VALUES (382099, 2, '09/30/2005 9:12AM')
> INSERT #HuonUpload_nb VALUES (382099, 1, '09/29/2005 11:36PM')
> INSERT #HuonUpload_nb VALUES (382099, 4, '09/29/2005 09:45AM')
> INSERT #HuonUpload_nb VALUES (382099, 2, '09/28/2005 01:18PM')
> INSERT #HuonUpload_nb VALUES (374943, 3, '10/03/2005 11:26AM')
> INSERT #HuonUpload_nb VALUES (374943, 2, '10/03/2005 10:20AM')
> INSERT #HuonUpload_nb VALUES (374943, 1, '10/03/2005 10:15AM')
> INSERT #HuonUpload_nb VALUES (376279, 1, '09/13/2005 2:19PM')
> INSERT #HuonUpload_nb VALUES (376279, 2, '09/13/2005 2:36PM')
> go
> SELECT *
> FROM #Policy_nb
> GO
> Policy_Id CurrAgent_id UploadTp_id
> -- -- --
> 382099 4894 3
> 374943 614 3
> 376279 4710 2
> SELECT *
> FROM #HuonUpload_nb
> GO
> Policy_id UploadTp_Id UploadStatus_dt
> -- -- --
> 382099 3 2005-10-03 11:27:00.000
> 382099 2 2005-10-03 11:25:00.000
> 382099 1 2005-10-03 11:21:00.000
> 382099 4 2005-09-30 09:24:00.000
> 382099 1 2005-09-30 09:22:00.000
> 382099 2 2005-09-30 09:21:00.000
> 382099 2 2005-09-30 09:12:00.000
> 382099 1 2005-09-29 23:36:00.000
> 382099 4 2005-09-29 09:45:00.000
> 382099 2 2005-09-28 13:18:00.000
> 374943 3 2005-10-03 11:26:00.000
> 374943 2 2005-10-03 10:20:00.000
> 374943 1 2005-10-03 10:15:00.000
> 376279 1 2005-09-13 14:19:00.000
> 376279 2 2005-09-13 14:36:00.000
>
> -- Rules: Return only these rows which has UploadTp_id = 1, 2 and 3.
> --Testing... Not working...
> SELECT a.CurrAgent_id,
> b.Policy_id,
> b.UploadTp_Id,
> b.UploadStatus_dt
> FROM #Policy_nb AS a
> JOIN #HuonUpload_nb AS b
> ON a.Policy_id = b.Policy_id
> JOIN (SELECT TOP 100 PERCENT Policy_id, UploadTp_id,
> MAX(UploadStatus_dt) AS 'UploadStatus_dt'
> FROM #HuonUpload_nb
> WHERE UploadTp_id IN (1, 2, 3)
> GROUP BY Policy_id, UploadTp_id
> ORDER BY Policy_id ASC, UploadStatus_dt DESC) AS c
> ON c.Policy_id = b.Policy_id
> AND c.UploadTp_id = b.UploadTp_id
> AND c.UploadStatus_dt = b.UploadStatus_dt
> ORDER BY b.Policy_id DESC, b.UploadStatus_dt DESC
> GO
> --Result want:
> CurrAgent_id Policy_id UploadTp_Id UploadStatus_dt
> -- -- -- --
> 4894 382099 3 2005-10-03 11:27:00.000
> 4894 382099 2 2005-10-03 11:25:00.000
> 4894 382099 1 2005-10-03 11:21:00.000
> 614 374943 3 2005-10-03 11:26:00.000
> 614 374943 2 2005-10-03 10:20:00.000
> 614 374943 1 2005-10-03 10:15:00.000
>

Help with SELECT

Can anyone point me in the right direction, the code below returns results but the date range imposed by the BETWEEN command doesn't seem to work, asall the results from the table are shown.

<asp:SqlDataSourceID="ResultsSqlDataSource1"runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT venue, town, artist, date FROM gigs
WHERE (town +' (Town)' = @.town) OR (venue +' (Venue)' = @.venue) OR (artist +' (Artist)' = @.artist)
AND date BETWEEN CONVERT(DATETIME,'25/11/2007',103) AND CONVERT(DATETIME, '26/11/2007',103)">
<SelectParameters>
<asp:controlparameterControlID="TextBox1"Name="town"PropertyName="Text"/>
<asp:controlparameterControlID="TextBox1"Name="venue"PropertyName="Text"/>
<asp:controlparameterControlID="TextBox1"Name="artist"PropertyName="Text"/>
</SelectParameters>
</asp:SqlDataSource>

Regards

Tino

What format is your date column in the DB table? You can try using:

WHERE...AND date <='25/11/2007' AND date >= '26/11/2007'

Hope this helps,

Vivek

|||

Vivek

Do you mean the date type, if so its a datetime.

Thanks

Tino

|||

Hitinomclaren ,

try like this

ANDCONVERT(DATETIME,'date',101) BETWEEN CONVERT(DATETIME,'2007-11-25',101) AND CONVERT(DATETIME,'2007-11-26',101)

or

AND (date > '2007-11-25' anddate < '2007-11-26' )

Regards,
Shri

|||

Its a good practice to apply the conversion to all the participants in any comparison. So, your query should be like

"SELECT DISTINCT venue, town, artist, date FROM gigs
WHERE (town +' (Town)' = @.town) OR (venue +' (Venue)' = @.venue) OR (artist +' (Artist)' = @.artist)
ANDCONVERT(DATETIME,date,103) BETWEEN CONVERT(DATETIME,'25/11/2007',103) AND CONVERT(DATETIME, '26/11/2007',103)"

Hope this helps.

|||

Thanks for suggestions, they didn't work for me

I really think im missing something fundamental now because all the posts i've trawled through have suggested similar solutions.

After 2 days at this one problem im trying not to get down but its really getting hard nowIndifferent

My database is SQLExpress and i've used the datetime datatype in the date colum on the DB. Im using VS2008 beta 2.

I have 20 test records in my DB and all have the date column filled in, im not using thetimepart but they are there in the DB and all default to midnight 00:00:00.

I dont know how to use stored procedures yet but im looking at the video tutorial form thelearn part of this site to hopfully get to grips with it, im assuming that the examples you have given me will work in either on the page (in the SqlDataSource as above) or in a Stored Procedure. Is there any Difference in the Syntax when switching between the two?

When I tried the suggestions you gave me using the Convert way I get ALL the records in the DB and when I use the < > way I get No records.

What am i doing wrong?

thx

tino

|||

Can you post the table structure along with some sample records, so that we can understand your problem better ?

|||

Here's the Table structure......

Coumn Name Data Type

gigId int ---> Primary Key, Is Identity-->Yes

venue varchar(50)

town varchar(50)

artist varchar(50

date datetime

I've looked at the datatypes available and there isn't just a date (without the time) must be an SqlExpress thing.

I cant even hard code 1 date in the SELECT command i.e.

SelectCommand="SELECT DISTINCT venue, town, artist, date FROM gigs WHERE (town + ' (Town)' = @.town) OR (venue + ' (Venue)' = @.venue) OR (artist + ' (Artist)' = @.artist)AND (date = '25/11/2007') ">

Crying

thx tino

|||

tinomclaren:

Thanks for suggestions, they didn't work for me

I really think im missing something fundamental now because all the posts i've trawled through have suggested similar solutions.

Yes, you are missing something fundamental. :)

You cannot mix AND with OR as you have done and expect to get correct results.

In your example, all the ORs need to be within a set of () .

() must be used to delimit the logic boundaries of the ANDs and ORs.

Example:

If I tell you I will only date women who have red hair and blue eyes or green eyes, what do I mean?

Do I mean the women must have red hair - then they must also have blue eyes or green eyes?

Or would a blonde with green eyes qualify?

My original statement was ambiguous.

If, instead, I said, "I will only date women with red hair and (blue eyes or green eyes)", then the blonde with green eyes won't qualify.

If I said "I will only date women with (red hair and blue eyes) or green eyes" then the blonde with green eyes will qualify. So would a redhead with green eyes, for that matter.

HTH

|||

David,

Once again you have saved my life. I can only hope that one day I will be as experienced as you.

Two days for 2 brackets........I wont forget this.

Thankyou

Tino

|||

Thanks everyone for your help....All answers turned out to be correct......this forum is simply superb :)

For anyone with a similar problem here is the final code I used, which works perfectly....

<asp:SqlDataSourceID="ResultsSqlDataSource1"runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT venue, town, artist, date FROM gigs WHERE((town + ' (Town)' = @.town) OR (venue + ' (Venue)' = @.venue) OR (artist + ' (Artist)' = @.artist)) AND CONVERT(DATETIME,date,103) BETWEEN CONVERT(DATETIME,'25/11/2007',103) AND CONVERT(DATETIME, '26/11/2007',103) ORDER BY date asc">
<SelectParameters>
<asp:controlparameterControlID="TextBox1"Name="town"PropertyName="Text"/>
<asp:controlparameterControlID="TextBox1"Name="venue"PropertyName="Text"/>
<asp:controlparameterControlID="TextBox1"Name="artist"PropertyName="Text"/>
</SelectParameters>
</asp:SqlDataSource>

Brackets inbold made the whole thing work correctly

thnx

Tino

Help with script and variables

Hi If I try to run the code below I get the following errors

Server: Msg 156, Level 15, State 1, Line 36
Incorrect syntax near the keyword 'view'.
Server: Msg 170, Level 15, State 1, Line 51
Line 51: Incorrect syntax near '@.month1'.

I am not sure why it does not like the keyword view ? also I am trying to use the variables in the column name of the create table but again it does not like this.

-- declare all variables!

DECLARE @.startdate datetime,
@.enddate datetime,
@.enddate1 datetime,
@.month1 char,
@.month2 char,
@.month3 char


-- declare the cursor

DECLARE call_data CURSOR FOR


SELECT dbo.removetime(DATEADD(month, -3, getdate())) as startdate,
dbo.removetime(DATEADD(month, -2, getdate())-1) as enddate,
dbo.removetime(DATEADD(month, 0, getdate())-1) as enddate1,
left(dbo.removetime(DATEADD(month, -3, getdate())),5) as month1,
left( dbo.removetime(DATEADD(month, -2, getdate())-1),4) as month2,
left(dbo.removetime(DATEADD(month, 0, getdate())-1),4) as month3

OPEN call_data

FETCH call_data INTO @.startdate,
@.enddate,
@.enddate1,
@.month1,
@.month2,
@.month3

BEGIN

--run SQL statements

drop view temp_view

create view temp_view as
select column1,column2
from some_table
where date_and_time >= @.startdate
and date_and_time <= @.enddate1

drop table temp_table

create table temp_table (
account_no int,
account_holder_surname varchar(80),
account_holder_forename varchar(80),
@.month1 money,
@.month2 money,
@.month3 money
)

END

CLOSE call_data

DEALLOCATE call_data

RETURN


For starters, the CREATE VIEW statement has to be the first statement in a batch so it can't be used in this way.

You could dynamically create your CREATE VIEW statement then use sp_executesql to execute the command.

Chris

|||

Hi thanks for the reply

I am quite new to this what do you mean by dynamically create the CREATE VIEW statement ?

|||

DECLARE @.startdate datetime,
@.enddate datetime,
@.enddate1 datetime,
@.month1 char,
@.month2 char,
@.month3 char


-- declare the cursor

DECLARE call_data CURSOR FOR


SELECT dbo.removetime(DATEADD(month, -3, getdate())) as startdate,
dbo.removetime(DATEADD(month, -2, getdate())-1) as enddate,
dbo.removetime(DATEADD(month, 0, getdate())-1) as enddate1,
left(dbo.removetime(DATEADD(month, -3, getdate())),5) as month1,
left( dbo.removetime(DATEADD(month, -2, getdate())-1),4) as month2,
left(dbo.removetime(DATEADD(month, 0, getdate())-1),4) as month3

OPEN call_data

FETCH call_data INTO @.startdate,
@.enddate,
@.enddate1,
@.month1,
@.month2,
@.month3

BEGIN

--run SQL statements

drop view temp_view

create view temp_view as
select column1,column2
from some_table
where date_and_time >= @.startdate -- you cant have variabl inside view
and date_and_time <= @.enddate1 -- you cant have variabl inside view

drop table temp_table

create table temp_table (
account_no int,
account_holder_surname varchar(80),
account_holder_forename varchar(80),
@.month1 money, -- Remove @.
@.month2 money, -- Remove @.
@.month3 money -- Remove @.

)

END

CLOSE call_data

DEALLOCATE call_data

RETURN

and also tell us what u are intended to do... there are couple of wrong sysntax in the script... you can not use variable inside a view definition...

Madhu

|||

Hi

First of I am trying to create a view of data between a specific date range. This is the last three months. So if it was to run today then the view would contain data from 1st nov 2006 to 28th feb 2007.

When it runs on the 1st Apr the view would contain data from 1st Dec to 31st march and so on. This is why I am trying to drop the view first then create it. I am then running a query on the view and inserting the results of this into the table i create in the script.

Secondly as I am working with a rolling 3 months of data I need to drop the table I insert the data into an create it again with the correct column headings ie NOV,DEC,JAN. This is why I have the variables in the create view and create table statements.

If this is not possible is their an other way of doing this ?

Hope that makes sense

|||

I wouldn't bother creating a View for temporary purposes, you can use the SELECT statement as is to directly insert data into tables.

Try the code below to drop and create your table - I see no need for a cursor in the scenario you have presented.

Chris

DECLARE @.startdate DATETIME

DECLARE @.enddate DATETIME

DECLARE @.enddate1 DATETIME

DECLARE @.month1 NVARCHAR(10)

DECLARE @.month2 NVARCHAR(10)

DECLARE @.month3 NVARCHAR(10)

DECLARE @.TableName NVARCHAR(100)

DECLARE @.SQLString NVARCHAR(4000)

SELECT @.startdate = dbo.removetime(DATEADD(month, -3, getdate())),

@.enddate = dbo.removetime(DATEADD(month, -2, getdate())-1),

@.enddate1 = dbo.removetime(DATEADD(month, 0, getdate())-1),

@.month1 = left(dbo.removetime(DATEADD(month, -3, getdate())),5),

@.month2 = left( dbo.removetime(DATEADD(month, -2, getdate())-1),4),

@.month3 = left(dbo.removetime(DATEADD(month, 0, getdate())-1),4)

--The name of the new table

SELECT @.TableName = N'Temp_Table'

--Build the string to drop the table

SET @.SQLString =

N'IF OBJECT_ID(' + QUOTENAME(@.TableName, '''') + ') IS NOT NULL DROP TABLE [' + @.TableName + '];'

--Build the string to create the table

SET @.SQLString = @.SQLString +

N'CREATE TABLE [' + @.TableName + ']

(

[account_no] int,

[account_holder_surname] varchar(80),

[account_holder_forename] varchar(80),

[' + @.month1 + '] money,

[' + @.month2 + '] money,

[' + @.month3 + '] money

)'

--Execute the statements

EXEC(@.SQLString)

--Prove that the new table exists

--EXEC sp_help 'Temp_Table'

/*

--Don't create a 'temporary' view - just use the query directly like this...

INSERT INTO.... / UPDATE etc...

select column1,column2

from some_table

where date_and_time >= @.startdate

and date_and_time <= @.enddate1

*/

|||

Hi Chris

Thanks so much. It was the syntax around the create table I could not get my head around !

Thanks

Wednesday, March 21, 2012

Help with rewriting code without cursor

Hello,
Just wondering if anyone can tell me the best way to rewrite the below code
without a cursor.
It's just passing each Id to a stored procedure.
Let me know if you need any more info.
Thanks & go easy on me, I know cursors tend to rile everyone up.
Declare cur_DeleteStuff Cursor Scroll For
Select distinct TableID
from tbl_DTM
Where APID IN
(Select TableID from tbl_DTM where
supplierID = @.v_FromSupplierID)
Open cur_DeleteStuff
Fetch First FROM cur_DeleteStiff into @.ChildTableID
While (@.@.Fetch_Status <> -1)
Begin
exec sp_SMART_ANADeleteFrom @.ChildTableID, 1, 0
If @.@.Error <> 0
BEGIN
ROLLBACK Transaction CDTTransfer
RAISERROR('Something Bad Happened, Updates ROLLED BACK!',1,1)
RETURN
END
Fetch Next FROM cur_Deletestuff into @.ChildTableID
END
Close cur_DeleteStuff
Deallocate cur_DeleteStuff"Lesley" <Lesley@.discussions.microsoft.com> wrote in message
news:F2C468A7-7573-4FE4-8FDC-D8D75D2AE374@.microsoft.com...
> Hello,
> Just wondering if anyone can tell me the best way to rewrite the below
> code
> without a cursor.
> It's just passing each Id to a stored procedure.
> Let me know if you need any more info.
> Thanks & go easy on me, I know cursors tend to rile everyone up.
>
What is the code for the stored procedure: sp_SMART_ANADeleteFrom
If the sp_SMART_ANADeleteFrom procedure is performing some type of delete
based on the ChildTableID
then you should be able to modify the delete to do something like the
following:
DELETE TableName
WHERE ChildTableID IN
(Select distinct TableID
from tbl_DTM
Where APID IN
(Select TableID from tbl_DTM where
supplierID = @.v_FromSupplierID))
One a side note: You should probably not be naming your user defined stored
procedures with an sp_ prefix. The sp_ prefix while not disallowed, is
generally use for SQL Server system stored procedure which are found in the
master database and are available globally throughout the system.
Rick Sawtell
MCT, MCSD, MCDBA|||Thanks for your help Rick,
Though the naming convention implies it's only deleting a child - it's
actually doing something completely different.
I still need to call the stored procedure for each table ID found.
Thanks for the sp_ info.
Lesley
"Rick Sawtell" wrote:

> "Lesley" <Lesley@.discussions.microsoft.com> wrote in message
> news:F2C468A7-7573-4FE4-8FDC-D8D75D2AE374@.microsoft.com...
> What is the code for the stored procedure: sp_SMART_ANADeleteFrom
> If the sp_SMART_ANADeleteFrom procedure is performing some type of delete
> based on the ChildTableID
> then you should be able to modify the delete to do something like the
> following:
> DELETE TableName
> WHERE ChildTableID IN
> (Select distinct TableID
> from tbl_DTM
> Where APID IN
> (Select TableID from tbl_DTM where
> supplierID = @.v_FromSupplierID))
>
> One a side note: You should probably not be naming your user defined stor
ed
> procedures with an sp_ prefix. The sp_ prefix while not disallowed, is
> generally use for SQL Server system stored procedure which are found in th
e
> master database and are available globally throughout the system.
> Rick Sawtell
> MCT, MCSD, MCDBA
>
>|||Whatever it does, we can't help you find a set-baset solution without you
posting the procedure.
ML|||Sorry, I was thinking I could just use the sp as is. I pasted it below. It
was written a while ago by someone else & is in production now.
Basically it's deleting rows from a table, then deleting the defining row
from another table based on the tableID
I'd welcome any input on how to change this to set based.
That may also address rollback issues I predict I will have.
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
ALTER PROCEDURE sp_SMART_ANADeleteFrom
@.FromTableID INT = 0,
@.OKtoDeleteORIG BIT = 0,
@.DebugMode INT = 0
AS
DECLARE @.TableType CHAR(3)
DECLARE @.AnalyticParentID INT
DECLARE @.FromPhysicalTableName varchar(255)
DECLARE @.strSQL nvarchar(2000)
if @.FromTableID is null
begin
raiserror ('Invalid From Table ID.',1,1)
return
end
--
SELECT @.TableType = MyType,
@.AnalyticParentID = AnalyticParentID,
@.FromPhysicalTableName = PhysicalDataTableName
from
tbl_DataTableMaster where Tableid = @.FromTableID
BEGIN TRANSACTION DELETEfromAnalytics
-- Delete the rows from the Quarterly ANA table
SET @.StrSQL = N'DELETE FROM My_Users.' + @.FromPhysicalTableName +
N' WHERE TableID = ' + rtrim(convert(char(10),@.FromTableID))
if @.DebugMode <> 0
begin
print '-- DELETE Statement --'
print @.strsql
end
EXEC (@.StrSQL)
if @.@.Error <> 0
begin
ROLLBACK Transaction
Raiserror('Error deleting rows. Table Deletion did NOT occur!!',1,1)
RETURN
end
--delete row from tbl_DataTableMaster
SET @.strSQL = N'DELETE FROM tbl_DataTableMaster ' +
N' WHERE TableID = ' + rtrim(convert(char(10),@.FromTableID))
if @.DebugMode <> 0
begin
print '-- DELETE data table master Statement --'
print @.strsql
end
EXEC (@.StrSQL)
if @.@.Error <> 0
begin
ROLLBACK Transaction
Raiserror('Error Deleting in Data Table Master. Table Deletion did NOT
occur!!',1,1)
RETURN
end
--
COMMIT TRANSACTION DELETEfromAnalytics
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GOsql

Help with returning too much data

I am running the below query and getting back results that have the word
"mode" in it. Isn't the keyword CONTAINS supposed to treat my search
expression as one word? Can someone show me what is wrong with this query so
that it returns only records that have the exact search expression "mode-4"
in it? Thank you.
SELECT MyFields
FROM MyTable M
LEFT JOIN Table1 T1 ON T1.Field1 = M.Field1
LEFT JOIN Table2 T2 ON T2.Field1 = M.Field2
LEFT JOIN Table3 T3 ON T3.Field1 = M.Field3
LEFT JOIN Table4 T4 ON T4.Field1 = M.Field4
WHERE CONTAINS( M.* , '"mode-4"' ) ORDER BY M.Field1
are the fields in Table1, Table2, Table3, Table4 and MyFields fulltext
indexed or are they integer values?
Hilary Cotter
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
Looking for a FAQ on Indexing Services/SQL FTS
http://www.indexserverfaq.com
"Mike Collins" <MikeCollins@.discussions.microsoft.com> wrote in message
news:82826E0A-C56B-4B47-B811-95F8F7075530@.microsoft.com...
>I am running the below query and getting back results that have the word
> "mode" in it. Isn't the keyword CONTAINS supposed to treat my search
> expression as one word? Can someone show me what is wrong with this query
> so
> that it returns only records that have the exact search expression
> "mode-4"
> in it? Thank you.
> SELECT MyFields
> FROM MyTable M
> LEFT JOIN Table1 T1 ON T1.Field1 = M.Field1
> LEFT JOIN Table2 T2 ON T2.Field1 = M.Field2
> LEFT JOIN Table3 T3 ON T3.Field1 = M.Field3
> LEFT JOIN Table4 T4 ON T4.Field1 = M.Field4
> WHERE CONTAINS( M.* , '"mode-4"' ) ORDER BY M.Field1
|||Not sure what you mean by "are they integer values", but the table that
contains MyFields is full-text indexed. Do tables 1,2,3, and 4 need to be
full-text indexed? Course, I'm thinking yes since you asked the question
"Hilary Cotter" wrote:

> are the fields in Table1, Table2, Table3, Table4 and MyFields fulltext
> indexed or are they integer values?
> --
> Hilary Cotter
> Looking for a SQL Server replication book?
> http://www.nwsu.com/0974973602.html
> Looking for a FAQ on Indexing Services/SQL FTS
> http://www.indexserverfaq.com
>
> "Mike Collins" <MikeCollins@.discussions.microsoft.com> wrote in message
> news:82826E0A-C56B-4B47-B811-95F8F7075530@.microsoft.com...
>
>
|||Perhaps if you could post the schema. For the record mode-4 is indexed and
queried two separate words. If 4 is not in your noise word list this should
work.
Hilary Cotter
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
Looking for a FAQ on Indexing Services/SQL FTS
http://www.indexserverfaq.com
"Mike Collins" <MikeCollins@.discussions.microsoft.com> wrote in message
news:E3738AD4-7A01-40C2-95DB-A968D423B247@.microsoft.com...[vbcol=seagreen]
> Not sure what you mean by "are they integer values", but the table that
> contains MyFields is full-text indexed. Do tables 1,2,3, and 4 need to be
> full-text indexed? Course, I'm thinking yes since you asked the question
>
> "Hilary Cotter" wrote:
|||Sorry, but our company specifically prohibits posting any schema details in
newsgroups, but should the order be:
1. Remove words from the noise list.
2. Create the full-text index.
I'm wondering that since I created the index before removing the 4 from the
noise list, that it may be the reason my search is not working.
"Hilary Cotter" wrote:

> Perhaps if you could post the schema. For the record mode-4 is indexed and
> queried two separate words. If 4 is not in your noise word list this should
> work.
> --
> Hilary Cotter
> Looking for a SQL Server replication book?
> http://www.nwsu.com/0974973602.html
> Looking for a FAQ on Indexing Services/SQL FTS
> http://www.indexserverfaq.com
>
> "Mike Collins" <MikeCollins@.discussions.microsoft.com> wrote in message
> news:E3738AD4-7A01-40C2-95DB-A968D423B247@.microsoft.com...
>
>
|||OK, let me guess your schema then from what you have posted.
Create MyFields(PK int not null identity primary key, Fields1 char(20),
Field2 char(20), Field3 char(20), Field4 char(20))
Create T1 (pk int not null references MyFields(PK), Field1 char(20))
Create T2 (pk int not null references MyFields(PK), Field2 char(20))
Create T3 (pk int not null references MyFields(PK), Field3 char(20))
Create T4 (pk int not null references MyFields(PK), Field4 char(20))
This is kind of critical as I think your join condition is all wrong.
But you are correct with a search on mode-4 and you have removed 4 from your
noise word list after building your index you will not get correct results.
In fact you should get fewer results which makes me wonder about your join
condition.
Hilary Cotter
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
Looking for a FAQ on Indexing Services/SQL FTS
http://www.indexserverfaq.com
"Mike Collins" <MikeCollins@.discussions.microsoft.com> wrote in message
news:15E5FCB3-0A36-4B0E-97D0-C0E62376B759@.microsoft.com...[vbcol=seagreen]
> Sorry, but our company specifically prohibits posting any schema details
> in
> newsgroups, but should the order be:
> 1. Remove words from the noise list.
> 2. Create the full-text index.
> I'm wondering that since I created the index before removing the 4 from
> the
> noise list, that it may be the reason my search is not working.
> "Hilary Cotter" wrote:
|||The join condition is there because there are many other items that we are
building a where clause on. I simplified the query to what I thought was most
necessary and only included the joins to be true to my actual query, but with
what you have said about creating the full-text after removing the number 4
from the noise file, now I do not think they matter. If I could show you the
actual schema, I think you would agree with me.
Thank you very much for your time. I'll recreate the full-text index, after
removing any noise words, and see how it works for me then.
"Hilary Cotter" wrote:

> OK, let me guess your schema then from what you have posted.
> Create MyFields(PK int not null identity primary key, Fields1 char(20),
> Field2 char(20), Field3 char(20), Field4 char(20))
> Create T1 (pk int not null references MyFields(PK), Field1 char(20))
> Create T2 (pk int not null references MyFields(PK), Field2 char(20))
> Create T3 (pk int not null references MyFields(PK), Field3 char(20))
> Create T4 (pk int not null references MyFields(PK), Field4 char(20))
> This is kind of critical as I think your join condition is all wrong.
> But you are correct with a search on mode-4 and you have removed 4 from your
> noise word list after building your index you will not get correct results.
> In fact you should get fewer results which makes me wonder about your join
> condition.
> --
> Hilary Cotter
> Looking for a SQL Server replication book?
> http://www.nwsu.com/0974973602.html
> Looking for a FAQ on Indexing Services/SQL FTS
> http://www.indexserverfaq.com
>
> "Mike Collins" <MikeCollins@.discussions.microsoft.com> wrote in message
> news:15E5FCB3-0A36-4B0E-97D0-C0E62376B759@.microsoft.com...
>
>
|||MS changed the worbreaker in windows 2003, to contain what I consider
is now a bug.
The hyphen in 'mode-4' is actually now used to split the phrase into 2
words, therefore doing an OR search, hence returning every record with
'mode' OR '4' in it, which I expect will be quite a few.
On windows 2000, this worked properly to join the word, as a hyphen is
actually supposed to in text.
Eventually I got around it by replacing all hyphens in the indexed
text with HYP ie 'modeHYP4'. You need to replace any hyphens that
users enter in the search to the same.
Lots of our product skus had hyphens in so it was causing all sorts of
problems, 21-500 was returning thousands of results instead of 1.
Hope this helps...
On 14 Feb, 19:35, Mike Collins <MikeColl...@.discussions.microsoft.com>
wrote:
> The join condition is there because there are many other items that we are
> building a where clause on. I simplified the query to what I thought was most
> necessary and only included the joins to be true to my actual query, but with
> what you have said about creating the full-text after removing the number 4
> from the noise file, now I do not think they matter. If I could show you the
> actual schema, I think you would agree with me.

help with restore filegroup

hi !
I need help with restore a filegroup. Below are steps
which I made, what is wrong '
Steps:
- create a new filegroup "SE" and assign to it a few
tables. - OK
- make a backup new created filegroup "SE" - OK
- make a backup log file - OK
- drop one table "A1" from filegroup "SE" - OK
- make a backup log file (necessary to restore)- OK
- make a restore filegroup "SE" and log files - OK
my question is why after restore filegroup I haven't
droppped table "A1" '
I readed a documentation on microsoft - I think that all
is done ok.
Maybe I missing some details or something else '
thank for any answer, and sorry for my english The table A! should not be there after the file group restore. Are you
saying that it is there? If so, can you please post the CREATE DATABASE,
CREATE TABLE, ALTER DATABASE, BACKUP and RESTORE statements with which we
can reproduce this? It is always easier to talk about these things when
having statements available instead of guessing what you are doing (and
possibly how you are clicking etc in Enterprise Manager).
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
"rafal" <anonymous@.discussions.microsoft.com> wrote in message
news:198701c410c8$0e2a66e0$3501280a@.phx.gbl...
> hi !
> I need help with restore a filegroup. Below are steps
> which I made, what is wrong '
> Steps:
> - create a new filegroup "SE" and assign to it a few
> tables. - OK
> - make a backup new created filegroup "SE" - OK
> - make a backup log file - OK
> - drop one table "A1" from filegroup "SE" - OK
> - make a backup log file (necessary to restore)- OK
> - make a restore filegroup "SE" and log files - OK
> my question is why after restore filegroup I haven't
> droppped table "A1" '
> I readed a documentation on microsoft - I think that all
> is done ok.
> Maybe I missing some details or something else '
> thank for any answer, and sorry for my english |||hi again
thanks for answer Tibor,
Where is my problem ? - I have a database where are some
tables. A few from them grow up much more than rest. My
problem is to backup often tables where is bigger increase
of rows. Then I created a group and assigned to it these
tables with big increase of rows.
What I want to do ? - I want to backup only one group
which I created.
Here is the example code that I execute in QueryAnalyzer.
All of them are executed without errors but result is not
satisfactory
Steps:
1. create database:
CREATE DATABASE TEST
ON PRIMARY
( NAME = TEST_dat,
FILENAME = 'c:\program files\microsoft sql
server\mssql\data\testDat.mdf',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 15% ),
FILEGROUP TestGroup1
( NAME = TESTGROUP_dat,
FILENAME = 'c:\program files\microsoft sql
server\mssql\data\TestGroupDat.ndf',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 5 )
LOG ON
( NAME = 'TEST_log',
FILENAME = 'c:\program files\microsoft sql
server\mssql\data\TestLog.ldf',
SIZE = 5MB,
MAXSIZE = 25MB,
FILEGROWTH = 5MB )
2. use database
use test
3. create tables in database
first
create table A1 (
id int,
name char(50),
age int
)
ON 'TestGroup1'
second
create table A2(
id int,
field char(50)
)
ON 'PRIMARY'
4. insert example data
insert a2 values (1,'third')
insert a1 values (1,'Czesiek',12)
insert a1 values (2,'Wieseik',23)
insert a1 values (3,'Misiek',42)
5. backup interesting group
backup database test filegroup = 'testgroup1'
to disk = 'c:\testdb\gr1.bak'
6.backup log
backup log test
to disk ='c:\testdb\testlog.log'
7. delete data on table a1 (simulate losing data)
delete from a1 where age > 12
8. backup log (needed to restore filegroup)
backup log test
to disk = 'c:\testdb\beforRestore.log'
9. restore group
restore database test
file = 'testgroup_dat',
filegroup ='testgroup1'
from disk = 'c:\testdb\gr1.bak'
10. restore log
restore log test
from disk = 'c:\testdb\testlog.log'
with norecovery
11.restore last log
restore log test
from disk = 'c:\testdb\beforrestore.log'
with recovery
Is it done in a good order or not ?
Why after restore group and all log files I haven't
deleted in step 7 data ?
any suggestion ?
where is bug ?
thanks, rafal|||I'm not 100% certain on what you want to achieve, but I guess that you want
to undo the deletions. However,
you cannot use filegroup backup for this. When you do a restore of a partial
backup (file or filegroup), you
have to restore all log backups taken after that point in time, including th
at last one. No point in time, as
SQL server wouldn't know how to synchronize the work done against the filegr
oup (which you do not restore in
full) to the other part of the database. This is all documented in Books Onl
ine. If you want to communicate
this further, please use my below script. I have revised it a bit, so you do
n't have to create directories,
and also so you can execute it all in one go.
DROP DATABASE TEST
GO
CREATE DATABASE TEST
ON PRIMARY
( NAME = TEST_dat,
FILENAME = 'c:\testDat.mdf',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 15% ),
FILEGROUP TestGroup1
( NAME = TESTGROUP_dat,
FILENAME = 'c:\TestGroupDat.ndf',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 5 )
LOG ON
( NAME = 'TEST_log',
FILENAME = 'c:\TestLog.ldf',
SIZE = 5MB,
MAXSIZE = 25MB,
FILEGROWTH = 5MB )
GO
--2. use database
USE test
--3. create tables in databasefirst
create table A1 ( id int, name char(50), age int ) ON 'TestGroup1'
--second
create table A2( id int, field char(50) ) ON 'PRIMARY'
--4. insert example data
insert a2 values (1,'third')
insert a1 values (1,'Czesiek',12)
insert a1 values (2,'Wieseik',23)
insert a1 values (3,'Misiek',42)
--5. backup interesting group
backup database test filegroup = 'testgroup1' to disk = 'c:\gr1.bak' WITH IN
IT
--backup database test to disk = 'c:\gr1.bak' WITH INIT
--6.backup log
backup log test to disk ='c:\testlog.log' WITH INIT
--7. delete data on table a1 (simulate losing data)
BEGIN TRAN x WITH MARK 'x'
delete from a1 where age > 12
COMMIT TRAN
--8. backup log (needed to restore filegroup)
backup log test to disk = 'c:\beforRestore.log' WITH INIT
--8.5 use master
USE master
--9. restore group
restore database test filegroup ='testgroup1' from disk = 'c:\gr1.bak'
--restore database test file = 'testgroup_dat', filegroup ='testgroup1' fro
m disk = 'c:\gr1.bak'
--restore database test from disk = 'c:\gr1.bak' with norecovery
--10. restore log
restore log test from disk = 'c:\testlog.log' with norecovery
--11.restore last log
restore log test from disk = 'c:\beforrestore.log' with recovery
, STOPBEFOREMARK = 'x'
GO
--Is the data still there?
SELECT * FROM test..a1
SELECT * FROM test..a2
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
"rafal" <anonymous@.discussions.microsoft.com> wrote in message news:1c4501c411a5$12e74940$3
a01280a@.phx.gbl...
> hi again
> thanks for answer Tibor,
> Where is my problem ? - I have a database where are some
> tables. A few from them grow up much more than rest. My
> problem is to backup often tables where is bigger increase
> of rows. Then I created a group and assigned to it these
> tables with big increase of rows.
> What I want to do ? - I want to backup only one group
> which I created.
> Here is the example code that I execute in QueryAnalyzer.
> All of them are executed without errors but result is not
> satisfactory
> Steps:
> 1. create database:
> CREATE DATABASE TEST
> ON PRIMARY
> ( NAME = TEST_dat,
> FILENAME = 'c:\program files\microsoft sql
> server\mssql\data\testDat.mdf',
> SIZE = 10,
> MAXSIZE = 50,
> FILEGROWTH = 15% ),
> FILEGROUP TestGroup1
> ( NAME = TESTGROUP_dat,
> FILENAME = 'c:\program files\microsoft sql
> server\mssql\data\TestGroupDat.ndf',
> SIZE = 10,
> MAXSIZE = 50,
> FILEGROWTH = 5 )
> LOG ON
> ( NAME = 'TEST_log',
> FILENAME = 'c:\program files\microsoft sql
> server\mssql\data\TestLog.ldf',
> SIZE = 5MB,
> MAXSIZE = 25MB,
> FILEGROWTH = 5MB )
> 2. use database
> use test
> 3. create tables in database
> first
> create table A1 (
> id int,
> name char(50),
> age int
> )
> ON 'TestGroup1'
> second
> create table A2(
> id int,
> field char(50)
> )
> ON 'PRIMARY'
> 4. insert example data
> insert a2 values (1,'third')
> insert a1 values (1,'Czesiek',12)
> insert a1 values (2,'Wieseik',23)
> insert a1 values (3,'Misiek',42)
> 5. backup interesting group
> backup database test filegroup = 'testgroup1'
> to disk = 'c:\testdb\gr1.bak'
> 6.backup log
> backup log test
> to disk ='c:\testdb\testlog.log'
> 7. delete data on table a1 (simulate losing data)
> delete from a1 where age > 12
> 8. backup log (needed to restore filegroup)
> backup log test
> to disk = 'c:\testdb\beforRestore.log'
> 9. restore group
> restore database test
> file = 'testgroup_dat',
> filegroup ='testgroup1'
> from disk = 'c:\testdb\gr1.bak'
> 10. restore log
> restore log test
> from disk = 'c:\testdb\testlog.log'
> with norecovery
> 11.restore last log
> restore log test
> from disk = 'c:\testdb\beforrestore.log'
> with recovery
>
> Is it done in a good order or not ?
> Why after restore group and all log files I haven't
> deleted in step 7 data ?
> any suggestion ?
> where is bug ?
> thanks, rafal

Monday, March 19, 2012

Help with Query.

Friends,
I have a table as shown below,
ABC DEF
23 2156
34 2156
41 2156
34 2157
38 2157
41 2157
I would like to return data for ABC column in a comma seperated format, I
would like to import the data into a new table.
23,34,41 2156
34,38,41 2157
How can i do that?
Any help is greatly appreciated.
TIA,
Santosh
Santhosh,
Here is an example. modify it to fit your schema.
CREATE TABLE Users(Uid int, Username VARCHAR(35))
CREATE TABLE Roles(Rid int, RoleName VARCHAR(35))
CREATE TABLE UserRoles(Uid int, Rid int)
Go
INSERT INTO Users VALUES(1, 'A')
INSERT INTO Users VALUES(2, 'B')
INSERT INTO Users VALUES(3, 'C')
INSERT INTO Users VALUES(4, 'D')
INSERT INTO Roles Values(1,'Admin')
INSERT INTO Roles Values(2,'Accounts')
INSERT INTO Roles Values(3,'Operations')
INSERT INTO Roles Values(4,'Marketing')
INSERT INTO UserRoles VALUES(1,1)
INSERT INTO UserRoles VALUES(1,4)
INSERT INTO UserRoles VALUES(2,3)
INSERT INTO UserRoles VALUES(2,4)
INSERT INTO UserRoles VALUES(3,1)
INSERT INTO UserRoles VALUES(3,2)
INSERT INTO UserRoles VALUES(3,3)
INSERT INTO UserRoles VALUES(4,2)
Go
CREATE Function dbo.GetRoles(@.Uid int)
RETURNS VARCHAR(400)
AS
BEGIN
DECLARE @.vchRoleList VARCHAR(400)
SET @.vchRoleList = ''
SELECT @.vchRoleList = @.vchRoleList +
CASE WHEN @.vchRoleList= '' THEN '' ELSE ', ' END + RoleName
FROM Roles R
INNER JOIN UserRoles UR
ON R.Rid = UR.Rid AND UR.UId = @.Uid
RETURN @.vchRoleList
END
GO
SELECT U.Uid, U.UserName, dbo.GetRoles(Uid)
FROM Users U
Roji. P. Thomas
Net Asset Management
https://www.netassetmanagement.com
"Santosh" <santoshNoSpam@.NoSpam.net> wrote in message
news:eIBVj844EHA.3368@.TK2MSFTNGP10.phx.gbl...
> Friends,
> I have a table as shown below,
> ABC DEF
> --
> 23 2156
> 34 2156
> 41 2156
> 34 2157
> 38 2157
> 41 2157
>
> I would like to return data for ABC column in a comma seperated format, I
> would like to import the data into a new table.
> 23,34,41 2156
> 34,38,41 2157
> How can i do that?
> Any help is greatly appreciated.
> TIA,
> --
> Santosh
>
>
|||It works.
Thanks,
Appreciate it.
Santosh
"Roji. P. Thomas" <thomasroji@.gmail.com> wrote in message
news:eD8U7354EHA.2624@.TK2MSFTNGP11.phx.gbl...
> Santhosh,
> Here is an example. modify it to fit your schema.
>
> CREATE TABLE Users(Uid int, Username VARCHAR(35))
> CREATE TABLE Roles(Rid int, RoleName VARCHAR(35))
> CREATE TABLE UserRoles(Uid int, Rid int)
> Go
> INSERT INTO Users VALUES(1, 'A')
> INSERT INTO Users VALUES(2, 'B')
> INSERT INTO Users VALUES(3, 'C')
> INSERT INTO Users VALUES(4, 'D')
> INSERT INTO Roles Values(1,'Admin')
> INSERT INTO Roles Values(2,'Accounts')
> INSERT INTO Roles Values(3,'Operations')
> INSERT INTO Roles Values(4,'Marketing')
>
> INSERT INTO UserRoles VALUES(1,1)
> INSERT INTO UserRoles VALUES(1,4)
> INSERT INTO UserRoles VALUES(2,3)
> INSERT INTO UserRoles VALUES(2,4)
> INSERT INTO UserRoles VALUES(3,1)
> INSERT INTO UserRoles VALUES(3,2)
> INSERT INTO UserRoles VALUES(3,3)
> INSERT INTO UserRoles VALUES(4,2)
> Go
> CREATE Function dbo.GetRoles(@.Uid int)
> RETURNS VARCHAR(400)
> AS
> BEGIN
> DECLARE @.vchRoleList VARCHAR(400)
> SET @.vchRoleList = ''
> SELECT @.vchRoleList = @.vchRoleList +
> CASE WHEN @.vchRoleList= '' THEN '' ELSE ', ' END + RoleName
> FROM Roles R
> INNER JOIN UserRoles UR
> ON R.Rid = UR.Rid AND UR.UId = @.Uid
> RETURN @.vchRoleList
> END
> GO
> SELECT U.Uid, U.UserName, dbo.GetRoles(Uid)
> FROM Users U
>
> --
> Roji. P. Thomas
> Net Asset Management
> https://www.netassetmanagement.com
>
> "Santosh" <santoshNoSpam@.NoSpam.net> wrote in message
> news:eIBVj844EHA.3368@.TK2MSFTNGP10.phx.gbl...
>

Help with Query.

Friends,
I have a table as shown below,
ABC DEF
--
23 2156
34 2156
41 2156
34 2157
38 2157
41 2157
I would like to return data for ABC column in a comma seperated format, I
would like to import the data into a new table.
23,34,41 2156
34,38,41 2157
How can i do that?
Any help is greatly appreciated.
TIA,
--
SantoshSanthosh,
Here is an example. modify it to fit your schema.
CREATE TABLE Users(Uid int, Username VARCHAR(35))
CREATE TABLE Roles(Rid int, RoleName VARCHAR(35))
CREATE TABLE UserRoles(Uid int, Rid int)
Go
INSERT INTO Users VALUES(1, 'A')
INSERT INTO Users VALUES(2, 'B')
INSERT INTO Users VALUES(3, 'C')
INSERT INTO Users VALUES(4, 'D')
INSERT INTO Roles Values(1,'Admin')
INSERT INTO Roles Values(2,'Accounts')
INSERT INTO Roles Values(3,'Operations')
INSERT INTO Roles Values(4,'Marketing')
INSERT INTO UserRoles VALUES(1,1)
INSERT INTO UserRoles VALUES(1,4)
INSERT INTO UserRoles VALUES(2,3)
INSERT INTO UserRoles VALUES(2,4)
INSERT INTO UserRoles VALUES(3,1)
INSERT INTO UserRoles VALUES(3,2)
INSERT INTO UserRoles VALUES(3,3)
INSERT INTO UserRoles VALUES(4,2)
Go
CREATE Function dbo.GetRoles(@.Uid int)
RETURNS VARCHAR(400)
AS
BEGIN
DECLARE @.vchRoleList VARCHAR(400)
SET @.vchRoleList = ''
SELECT @.vchRoleList = @.vchRoleList +
CASE WHEN @.vchRoleList= '' THEN '' ELSE ', ' END + RoleName
FROM Roles R
INNER JOIN UserRoles UR
ON R.Rid = UR.Rid AND UR.UId = @.Uid
RETURN @.vchRoleList
END
GO
SELECT U.Uid, U.UserName, dbo.GetRoles(Uid)
FROM Users U
Roji. P. Thomas
Net Asset Management
https://www.netassetmanagement.com
"Santosh" <santoshNoSpam@.NoSpam.net> wrote in message
news:eIBVj844EHA.3368@.TK2MSFTNGP10.phx.gbl...
> Friends,
> I have a table as shown below,
> ABC DEF
> --
> 23 2156
> 34 2156
> 41 2156
> 34 2157
> 38 2157
> 41 2157
>
> I would like to return data for ABC column in a comma seperated format, I
> would like to import the data into a new table.
> 23,34,41 2156
> 34,38,41 2157
> How can i do that?
> Any help is greatly appreciated.
> TIA,
> --
> Santosh
>
>|||It works.
Thanks,
Appreciate it.
--
Santosh
"Roji. P. Thomas" <thomasroji@.gmail.com> wrote in message
news:eD8U7354EHA.2624@.TK2MSFTNGP11.phx.gbl...
> Santhosh,
> Here is an example. modify it to fit your schema.
>
> CREATE TABLE Users(Uid int, Username VARCHAR(35))
> CREATE TABLE Roles(Rid int, RoleName VARCHAR(35))
> CREATE TABLE UserRoles(Uid int, Rid int)
> Go
> INSERT INTO Users VALUES(1, 'A')
> INSERT INTO Users VALUES(2, 'B')
> INSERT INTO Users VALUES(3, 'C')
> INSERT INTO Users VALUES(4, 'D')
> INSERT INTO Roles Values(1,'Admin')
> INSERT INTO Roles Values(2,'Accounts')
> INSERT INTO Roles Values(3,'Operations')
> INSERT INTO Roles Values(4,'Marketing')
>
> INSERT INTO UserRoles VALUES(1,1)
> INSERT INTO UserRoles VALUES(1,4)
> INSERT INTO UserRoles VALUES(2,3)
> INSERT INTO UserRoles VALUES(2,4)
> INSERT INTO UserRoles VALUES(3,1)
> INSERT INTO UserRoles VALUES(3,2)
> INSERT INTO UserRoles VALUES(3,3)
> INSERT INTO UserRoles VALUES(4,2)
> Go
> CREATE Function dbo.GetRoles(@.Uid int)
> RETURNS VARCHAR(400)
> AS
> BEGIN
> DECLARE @.vchRoleList VARCHAR(400)
> SET @.vchRoleList = ''
> SELECT @.vchRoleList = @.vchRoleList +
> CASE WHEN @.vchRoleList= '' THEN '' ELSE ', ' END + RoleName
> FROM Roles R
> INNER JOIN UserRoles UR
> ON R.Rid = UR.Rid AND UR.UId = @.Uid
> RETURN @.vchRoleList
> END
> GO
> SELECT U.Uid, U.UserName, dbo.GetRoles(Uid)
> FROM Users U
>
> --
> Roji. P. Thomas
> Net Asset Management
> https://www.netassetmanagement.com
>
> "Santosh" <santoshNoSpam@.NoSpam.net> wrote in message
> news:eIBVj844EHA.3368@.TK2MSFTNGP10.phx.gbl...
>> Friends,
>> I have a table as shown below,
>> ABC DEF
>> --
>> 23 2156
>> 34 2156
>> 41 2156
>> 34 2157
>> 38 2157
>> 41 2157
>>
>> I would like to return data for ABC column in a comma seperated format, I
>> would like to import the data into a new table.
>> 23,34,41 2156
>> 34,38,41 2157
>> How can i do that?
>> Any help is greatly appreciated.
>> TIA,
>> --
>> Santosh
>>
>

Help with query -SQL Express and ASP.net

I am having trouble with the below query. This is attached to a SQLDataAdapter which in turn is connected to a grid view.

@.pram5 is a dropdownlist
all other perameters such as @.nw in the big OR statement are check boxes.

My tables look similar to this:

Company TblComodity TblRegion

PK CompanyID PK CommodityID PK RegionID
CompanyName FK CompanyID FK CompanyID
CommodityName North
South, East, etc

What I would am trying to do is have a user slect a commodity which is a distinct value from the comodity table. Then select by tick boxes locations, then in the grid view companies with possible locations and commoditys appear. My problem is even when I select a commodity and leave all tick boxes blank (false) the records still display - like its only filltering on commodity name. Can anyone help ? I can provide more info if needed

Here is my query:

SELECT TblCompany.CompanyID, TblCompany.CompanyName, TblRegion.NorthWest, TblRegion.NorthEast, TblRegion.SouthEast, TblRegion.SouthWest,
TblRegion.Scotland, TblRegion.Wales, TblRegion.Midlands, TblRegion.UKNational, TblRegion.EuropOotherThanUK, TblComodity.ComName
FROM TblCompany INNER JOIN
TblRegion ON TblCompany.CompanyID = TblRegion.CompanyID INNER JOIN
TblComodity ON TblCompany.CompanyID = TblComodity.CompanyID AND TblComodity.ComName = @.pram5
WHERE (TblRegion.NorthWest = @.nw) OR
(TblRegion.NorthEast = @.NE) OR
(TblRegion.SouthEast = @.se) OR
(TblRegion.SouthWest = @.sw) OR
(TblRegion.Scotland = @.scot) OR
(TblRegion.Wales = @.wal) OR
(TblRegion.Midlands = @.mid) OR
(TblRegion.EuropOotherThanUK = @.EU) AND (TblRegion.UKNational = @.UKN)More info needed: Are the ticks mapped to the appropiate parameters like @.sw ? What do you pass if the ticks are not selected ? Probably Null ? because of doing an OR, you will get all values which habe in one of the filtered columns the value null then.

HTH, Jens K. Suessmeyer.

http://www.sqlserver2005.de

Monday, March 12, 2012

Help with query

Hi,
I have a stored procedure (posted below) that returns a club ranking list
with fatsest to slowest time for a swim club based on
Stroke,Distance,Course,Gender,Age. Number of rows in the ranking is based on
the @.Rowcount variable passed in.
I would like to expand this query to return a the (single) fastest time per
strokeID held in the BBMD_Strokes table. I understand that I could use a
CURSOR with a SELECT StrokeID from BBMD_strokes and loop through the same
query , but have read that CURSORS should be avoided due to poor
performance. Is there a prefered option to solve this ?
Niclas
CREATE procedure dbo.BBMD_GetEventRecord
@.StrokeID int,
@.DistanceID int,
@.CourseID int,
@.GenderID int,
@.AgeID int,
@.RowCount int
AS
Set ROWCOUNT @.Rowcount
SELECT D.DistanceName + ' ' + S.StrokeName as EventName,U.LastName + ', ' +
U.firstname as Swimmer,
R.Result,G.GalaName, G.StartDate,X.DOB
FROM BBMD_Results R
JOIN BBMD_Events E ON R.Eventid=E.EventID
JOIN BBMD_Galas G ON R.GalaID=G.GalaID
JOIN BBMD_Strokes S ON E.strokeID=S.strokeID
JOIN BBMD_Distances D ON E.DistanceID=D.DistanceID
JOIN Users U ON R.UserID=U.UserID
JOIN BBMD_ExtUser X ON R.USERID=X.UserID
JOIN (SELECT R.UserID,MIN(R.Result) as RES
FROM BBMD_Results R
JOIN BBMD_Events E ON R.EventID=E.EventID
JOIN BBMD_ExtUser X ON R.UserID=X.UserID
JOIN BBMD_Galas G ON R.GalaID=G.GalaID
WHERE
E.StrokeID=@.StrokeID AND
E.Distanceid=@.DistanceID AND
E.Genderid=@.GenderID AND
E.Courseid=@.CourseID AND
R.Resulttypeid=1 AND
DATEDIFF (YEAR, X.DOB, G.StartDate ) - CASE
WHEN 100 * MONTH(G.StartDate) + DAY(G.StartDate)
< 100 * MONTH(X.DOB) + DAY(X.DOB)
THEN 1 ELSE 0 END
BETWEEN (SELECT YearMin From BBMD_YearGroups
WHERE YearGroupID= @.Age)
AND
(SELECT YearMax From BBMD_YearGroups WHERE YearGroupID= @.AgeID)
Group By R.UserID) AS MinR ON minR.Res=R.result
AND minR.UserID=R.UserID
GROUP BY U.Lastname,U.firstname,G.GalaName, MinR.Res,R.Result,
S.StrokeName,D.DistanceName, G.StartDate,X.DOB
ORDER BY RESULT
GOPlease send the table DDL and sample data as INSERT statements, and what the
expected output looks like. Without that information, we are guessing and
the quality of help is sub-optimal..
Arnie Rowland, YACE*
"To be successful, your heart must accompany your knowledge."
*Yet Another certification Exam
"Niclas" <lindblom_niclas@.hotmail.com> wrote in message
news:%23roRJf5lGHA.1488@.TK2MSFTNGP02.phx.gbl...
> Hi,
> I have a stored procedure (posted below) that returns a club ranking list
> with fatsest to slowest time for a swim club based on
> Stroke,Distance,Course,Gender,Age. Number of rows in the ranking is based
> on the @.Rowcount variable passed in.
> I would like to expand this query to return a the (single) fastest time
> per strokeID held in the BBMD_Strokes table. I understand that I could use
> a CURSOR with a SELECT StrokeID from BBMD_strokes and loop through the
> same query , but have read that CURSORS should be avoided due to poor
> performance. Is there a prefered option to solve this ?
> Niclas
> CREATE procedure dbo.BBMD_GetEventRecord
> @.StrokeID int,
> @.DistanceID int,
> @.CourseID int,
> @.GenderID int,
> @.AgeID int,
> @.RowCount int
> AS
> Set ROWCOUNT @.Rowcount
> SELECT D.DistanceName + ' ' + S.StrokeName as EventName,U.LastName + ', '
> + U.firstname as Swimmer,
> R.Result,G.GalaName, G.StartDate,X.DOB
> FROM BBMD_Results R
> JOIN BBMD_Events E ON R.Eventid=E.EventID
> JOIN BBMD_Galas G ON R.GalaID=G.GalaID
> JOIN BBMD_Strokes S ON E.strokeID=S.strokeID
> JOIN BBMD_Distances D ON E.DistanceID=D.DistanceID
> JOIN Users U ON R.UserID=U.UserID
> JOIN BBMD_ExtUser X ON R.USERID=X.UserID
> JOIN (SELECT R.UserID,MIN(R.Result) as RES
> FROM BBMD_Results R
> JOIN BBMD_Events E ON R.EventID=E.EventID
> JOIN BBMD_ExtUser X ON R.UserID=X.UserID
> JOIN BBMD_Galas G ON R.GalaID=G.GalaID
> WHERE
> E.StrokeID=@.StrokeID AND
> E.Distanceid=@.DistanceID AND
> E.Genderid=@.GenderID AND
> E.Courseid=@.CourseID AND
> R.Resulttypeid=1 AND
> DATEDIFF (YEAR, X.DOB, G.StartDate ) - CASE
> WHEN 100 * MONTH(G.StartDate) + DAY(G.StartDate)
> < 100 * MONTH(X.DOB) + DAY(X.DOB)
> THEN 1 ELSE 0 END
> BETWEEN (SELECT YearMin From BBMD_YearGroups
> WHERE YearGroupID= @.Age)
> AND
> (SELECT YearMax From BBMD_YearGroups WHERE YearGroupID= @.AgeID)
> Group By R.UserID) AS MinR ON minR.Res=R.result
> AND minR.UserID=R.UserID
> GROUP BY U.Lastname,U.firstname,G.GalaName, MinR.Res,R.Result,
> S.StrokeName,D.DistanceName, G.StartDate,X.DOB
> ORDER BY RESULT
> GO
>|||
> @.StrokeID int,
> @.DistanceID int,
> @.CourseID int,
> @.GenderID int,
> @.AgeID int,
> @.RowCount int
Why is everything in your world an identifier? Explain what an
"age_id" is? Likewise, what is a gender_id? Gee, everyone else uses
an ISO gender_code.
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, data types, etc. in
your schema are. Sample data is also a good idea, along with clear
specifications. It is very hard to debug code when you do not let us
see it.

Wednesday, March 7, 2012

Help with OPENXML

Hi all,
I have a XMLString Like given below :
<PF OrderID="1234">
<CF>Computer</CF>
<CF>Phone</CF>
<CF>Modem</CF>
</PF>
My Question is
how do I insert into a SqlServer table havinf the Following
fields:
ORderID ItemNAme
After using OPEnXMl the table should look like this
ORderID ItemNAme
1234 Computer
1234 Phone
1234 Modem
Any thoughts on this
Thanks in Advance
..NetHelpWanted
Try this:
DECLARE @.x nvarchar(2000)
SET @.x = '<PF OrderID="1234">
<CF>Computer</CF>
<CF>Phone</CF>
<CF>Modem</CF>
</PF>'
DECLARE @.h int
EXEC sp_xml_preparedocument @.h OUTPUT, @.x
SELECT * FROM OPENXML (@.h, 'PF/CF', 2)
WITH
(OrderID int '../@.OrderID',
ItemName nvarchar(20) './text()'
)
EXEC sp_xml_removedocument @.h
Cheers,
Graeme
--
Graeme Malcolm
Principal Technologist
Content Master Ltd.
www.contentmaster.com
www.microsoft.com/mspress/books/6137.asp
".NetHelpWanted" <sasijrao@.gmail.com> wrote in message
news:FCA22802-A90B-4C2C-997A-81B90186B580@.microsoft.com...
Hi all,
I have a XMLString Like given below :
<PF OrderID="1234">
<CF>Computer</CF>
<CF>Phone</CF>
<CF>Modem</CF>
</PF>
My Question is
how do I insert into a SqlServer table havinf the Following
fields:
ORderID ItemNAme
After using OPEnXMl the table should look like this
ORderID ItemNAme
1234 Computer
1234 Phone
1234 Modem
Any thoughts on this
Thanks in Advance
..NetHelpWanted

Help with one-to-many relation join

I have two tables defined below. I would like to join them but choose
only the record from tblb which has the highest value of BID.
I know the following is wrong and I need help. Thanks, larzeb.
SELECT MAX(A), MAX(B), MAX(C), MAX(D), MAX(Y), MAX(Z)
FROM tbla A
JOIN tblb B
ON A.AID = B.AID
GROUP BY A.AID
CREATE TABLE tbla (
AID int IDENTITY(1,1) NOT NULL ,
A char (10),
B char (10),
C char (10),
D char (10),
CONSTRAINT PK_ID PRIMARY KEY (AID)
)
CREATE TABLE tblb (
BID int IDENTITY(1, 1) NOT NULL ,
AID int NOT NULL ,
Y char (10),
Z char (10) ,
CONSTRAINT PK_B PRIMARY KEY (BID),
CONSTRAINT FK_B_A FOREIGN KEY (AID)
REFERENCES tbla (AID)
)Here are a few possibilities:
select A, B, C, D, Y, Z
from tbla A
join tblb B
on A.AID = B.AID
where not exists (
select * from tblb as B2
where B2.AID = B.AID
and B2.BID < B.BID
)
or
select A, B, C, D, Y, Z
from tbla A
join tblb B
on A.AID = B.AID
where B.BID in (
select max(BID) from tblb as B2
group by B2.AID
)
or
select A, B, C, D, Y, Z
from tbla A
join tblb B
on A.AID = B.AID
where B.BID = (
select max(BID)
from tblb as B2
where B2.AID = B.AID
)
Steve Kass
Drew University
larzeb wrote:

>I have two tables defined below. I would like to join them but choose
>only the record from tblb which has the highest value of BID.
>I know the following is wrong and I need help. Thanks, larzeb.
>SELECT MAX(A), MAX(B), MAX(C), MAX(D), MAX(Y), MAX(Z)
>FROM tbla A
>JOIN tblb B
> ON A.AID = B.AID
>GROUP BY A.AID
>CREATE TABLE tbla (
> AID int IDENTITY(1,1) NOT NULL ,
> A char (10),
> B char (10),
> C char (10),
> D char (10),
> CONSTRAINT PK_ID PRIMARY KEY (AID)
> )
>CREATE TABLE tblb (
> BID int IDENTITY(1, 1) NOT NULL ,
> AID int NOT NULL ,
> Y char (10),
> Z char (10) ,
> CONSTRAINT PK_B PRIMARY KEY (BID),
> CONSTRAINT FK_B_A FOREIGN KEY (AID)
> REFERENCES tbla (AID)
> )
>
>