Showing posts with label records. Show all posts
Showing posts with label records. Show all posts

Friday, March 30, 2012

Need to count and group in units of ten

ok
well this seems easy enough so here it is.
I have a list of some 131500 records with 98 distinct employees thus there are several thousand records per employee. I am using reporting services and I need to set up the graph in units of ten. Having 98 employees on one graph will not work so I need to break them up in units of ten. I can't seem to remember the sql I need to write to accomplish this

any thoughts?
km

Assuming you are using sql server 2005, Can you try using

row_number() over (order by employee_id) as EmpIndex

for getting unique IDs and then split them based on EmpIndex/10=1, ...=9 etc.

|||

I 'think' that it would be far easier to help you if you could provide the table DDL, some sample data in the form of INSERT statements, and a display of your desired results.

For help with that, check:http://www.aspfaq.com/5006

|||thanks for the quick response-- here is some of the sql I have been playing with

SELECT
PH_ado_dac_no as DacNumber,
PH_ado_bimon as BillMonth,
PH_ado_biyr as BillYear,
[GH2_GroupName_(_ado_Bill_seq_no_)]as BillSeqNumber,
[PH_GroupName_(_ado_subscriber_no_)],
GH3_ado_unt as Unt_Employee,
DE_ado_CHANNEL_SEIZURE_DT as ChannelSeizureDate,
DE_ado_tim as ChannelSeizureTime,
DE_ado_CALL_TO_CITY_DESC as Call_To_City,
DE_ado_CALL_TO_STATE_CODE as Call_To_State,
DE_ado_tn as Number_To_From,
DE_checkserv AS CallDurationMinSec,
ROW_NUMBER() OVER(ORDER BY GH3_ado_unt ASC)/10 AS 'groupID',
DE_ado_at_charge_amt as Usage_At_Charge_Amt,
DE_ado_toll_charge_amt AS LongDistance_Toll_Charge_Amt,
DE_ado_tot as Total,
GF3_checkservtot as TotalCheckServe,
GF3_Total as TotalMins,
GF3_ac as TotalLongDistanceCharge
FROM
[cdtable1]

GROUP BY
PH_ado_dac_no,
'groupID'

this looks like something I have been trying to use but does not give the desired results since there may be hundreds of entries within the dataset with the same emp_id. when I use row_number() over (order by employee_id) as EmpIndex /10, the same person has multiple EmpIndex's-- I need each employee to have one and only one EmpIndex and group those in units of ten.
thanks again
km

|||thanks for the response-- I posted some additional information to the post previous to yours

km
|||

I should have mentioned this, sorry, can you add partition by inside the Over() clause.

row_number() over ( partition by employee_id order by employee_id)

|||Great this is looking much better
appreciate your help :-)
km

Wednesday, March 28, 2012

Need to bulk insert quickly with .NET

Hi all, I hope this is the correct place for this post.
I need to write a service that will bulk insert 3 million+ records from a
fixed width formatted text file to an SQL Server table. When I started
importing these records I used Access to put the records into a table and
DTS to get the table into SQL server. This process took maybe 1/2 hour.
I then tried using .NET to import the data by grabbing the textfile into a
datatable in batches of 250 records and then updating to the SQL server
database with a DataAdaptor. This process took about 5 hours which is kind
of unacceptable.
Is there anyway to speed up this process? Can .NET access any bulk insert
functionality? I need to automate this process into a service and would
like to get it to run on the same order as the manual process, and I would
like to use a service programmed in .NET. If I could even call SQL to acess
bulk insert functionality on SQL Server that would be fine, but SQL Server
does not seem to support fixed width text files.ADO.NET doesn't have a built-in bulk insert capability. As I see it you have
several options to do this. But the best bet is to use the SQLCommand object
to call the T-SQL BULK INSERT statement. Other options include creating a
bcp format file and calling that from the .NET program. Likewise, you could
create a DTS package and call that use the .NET COM interop classes or you
could use DMO's BulkInsert object.
Michael O.
"Todd Burry" <tburry@.nospam.com> wrote in message
news:Xns94CAA6111D5C1mythstoddburrycom@.2
07.46.248.16...
> Hi all, I hope this is the correct place for this post.
> I need to write a service that will bulk insert 3 million+ records from a
> fixed width formatted text file to an SQL Server table. When I started
> importing these records I used Access to put the records into a table and
> DTS to get the table into SQL server. This process took maybe 1/2 hour.
> I then tried using .NET to import the data by grabbing the textfile into a
> datatable in batches of 250 records and then updating to the SQL server
> database with a DataAdaptor. This process took about 5 hours which is kind
> of unacceptable.
> Is there anyway to speed up this process? Can .NET access any bulk insert
> functionality? I need to automate this process into a service and would
> like to get it to run on the same order as the manual process, and I would
> like to use a service programmed in .NET. If I could even call SQL to
acess
> bulk insert functionality on SQL Server that would be fine, but SQL Server
> does not seem to support fixed width text files.|||Thanks for the help. I didn't realize that the BULK INSERT supports fixed
width files. That will work just fine.

Need to bulk insert quickly with .NET

Hi all, I hope this is the correct place for this post.
I need to write a service that will bulk insert 3 million+ records from a
fixed width formatted text file to an SQL Server table. When I started
importing these records I used Access to put the records into a table and
DTS to get the table into SQL server. This process took maybe 1/2 hour.
I then tried using .NET to import the data by grabbing the textfile into a
datatable in batches of 250 records and then updating to the SQL server
database with a DataAdaptor. This process took about 5 hours which is kind
of unacceptable.
Is there anyway to speed up this process? Can .NET access any bulk insert
functionality? I need to automate this process into a service and would
like to get it to run on the same order as the manual process, and I would
like to use a service programmed in .NET. If I could even call SQL to acess
bulk insert functionality on SQL Server that would be fine, but SQL Server
does not seem to support fixed width text files.
ADO.NET doesn't have a built-in bulk insert capability. As I see it you have
several options to do this. But the best bet is to use the SQLCommand object
to call the T-SQL BULK INSERT statement. Other options include creating a
bcp format file and calling that from the .NET program. Likewise, you could
create a DTS package and call that use the .NET COM interop classes or you
could use DMO's BulkInsert object.
Michael O.
"Todd Burry" <tburry@.nospam.com> wrote in message
news:Xns94CAA6111D5C1mythstoddburrycom@.207.46.248. 16...
> Hi all, I hope this is the correct place for this post.
> I need to write a service that will bulk insert 3 million+ records from a
> fixed width formatted text file to an SQL Server table. When I started
> importing these records I used Access to put the records into a table and
> DTS to get the table into SQL server. This process took maybe 1/2 hour.
> I then tried using .NET to import the data by grabbing the textfile into a
> datatable in batches of 250 records and then updating to the SQL server
> database with a DataAdaptor. This process took about 5 hours which is kind
> of unacceptable.
> Is there anyway to speed up this process? Can .NET access any bulk insert
> functionality? I need to automate this process into a service and would
> like to get it to run on the same order as the manual process, and I would
> like to use a service programmed in .NET. If I could even call SQL to
acess
> bulk insert functionality on SQL Server that would be fine, but SQL Server
> does not seem to support fixed width text files.
|||Thanks for the help. I didn't realize that the BULK INSERT supports fixed
width files. That will work just fine.

Monday, March 26, 2012

Need suggestion on loading a 50 million records table from Oracle

All,

I need to load a 50 million records table monthly. Any suggestion about the best/fast way to do it?

Thanks a lot

All

I tried today; it used 8 hours to load the data just from the Oracle table to the staging table on sql server 2005. It is unacceptable!!! There are must be a better way to do it.

In the data flow, there is only an OLE DB source (from Oracle) -> data conversion transformation(convert the CLOB type) > OLE DB target (SQL server 2005)

Do I need to do more in the data flow? What should I do?

Many Thanks

|||

There IS a better way of doing it. Scott Barrett has done loads of work on this sort of stuff and has written some great blogs on it. Especially this one: http://microsoftdw.blogspot.com/2005/11/final-storyhow-to-get-data-out-of.html.

Search this forum as well - you'll find loads of good stuff.

Lastly, if you do only one thing make sure its to read this fabulous post (http://www.sqljunkies.com/WebLog/donald_farmer/archive/2005/03/13/8819.aspx) on SSIS and Oracle from Donald Farmer, Group Program Manager for SSIS.

-Jamie

sql

Need SQL that will return all records which include a particular v

If I understand you, your table is of OrderItems... One record for each line
item on every order... If that's the case, then the query would look like th
is
Select Distinct OrderID
From OrderItems I
Where Exists
(Select * From OrderItems
Where OrderID = I.OrderID
And Item = 'A')
And Exists
(Select * From OrderItems
Where OrderID = I.OrderID
And Item = 'B')
or...
Select Distinct A.OrderID
From OrderItems A
Join OrderItems B
On B.OrderID = A.OrderID
Where A.Item = 'A'
And B.Item = 'B'
"Larry Woods" wrote:

> I have a situation where I have multiple records, let's say ORDERS, and I
> have a record for each line item included in an order. Now, I want to fin
d
> all ORDERS that includes item A and item G, for example. An ORDER could
> include many additional items but the ORDER #'s that I want returns must
> include AT LEAST item A and G.
> How do I do this?
> TIA,
> Larry Woods
>
>Thanks. I'm going with the join for now. But, here is the next question:
The output of the SELECT is a list of OrderID's. Assuming we have
'customerID' in the Order table AND we have 'customerState' in the Customer
table, how do I "expand" the selection to only give me customers from
California (value="CA"), for example?
Customer Table Order Table
orderID <<<< (SELECT
OrderID...etc.)
customerID <<<<<< customerID (foreign key)
customerState
Again, TIA,
Larry Woods
"CBretana" <cbretana@.areteIndNOSPAM.com> wrote in message
news:02D90644-CC28-4B8E-9AEF-41E6C30EB034@.microsoft.com...
> If I understand you, your table is of OrderItems... One record for each
line
> item on every order... If that's the case, then the query would look like
this
> Select Distinct OrderID
> From OrderItems I
> Where Exists
> (Select * From OrderItems
> Where OrderID = I.OrderID
> And Item = 'A')
> And Exists
> (Select * From OrderItems
> Where OrderID = I.OrderID
> And Item = 'B')
> or...
> Select Distinct A.OrderID
> From OrderItems A
> Join OrderItems B
> On B.OrderID = A.OrderID
> Where A.Item = 'A'
> And B.Item = 'B'
>
> "Larry Woods" wrote:
>
I
find|||On Sat, 12 Mar 2005 04:51:46 -0700, Larry Woods wrote:

>Thanks. I'm going with the join for now. But, here is the next question:
>The output of the SELECT is a list of OrderID's. Assuming we have
>'customerID' in the Order table AND we have 'customerState' in the Customer
>table, how do I "expand" the selection to only give me customers from
>California (value="CA"), for example?
>Customer Table Order Table
> orderID <<<< (SELECT
>OrderID...etc.)
> customerID <<<<<< customerID (foreign key)
> customerState
>Again, TIA,
Hi Larry,
SELECT o.OrderID
FROM Orders AS o
INNER JOIN Customers AS c
ON c.CustomerID = o.CustomerID
INNER JOIN (SELECT OrderID
FROM OrderItems
WHERE Item IN ('A', 'B')
GROUP BY OrderID
HAVING COUNT(*) = 2) AS oi
ON oi.OrderID = o.OrderID
WHERE c.CustomerState = 'CA'
(untested - see www.aspfaq.com/5006 for the steps required to get a
tested solution)
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)sql

Friday, March 23, 2012

Need sql query

I have one table called attributes and have one records likethis

ID qty1 price1 qty2 price2 qty3 price3 qty4 price4

1 1 10 5 8 10 6 20 4

Now I want query to get prices if I enter qty=2 then itshould return 10 and 8 prices.

And if I enter qty=15 then it should returns prices 6 and 4.

In sort maximum and minimum prices of qty.

Thanks

Your logic isn't, well, logical. If you enter Quantity=2, you want the one below 2 and the one above. If you enter Quantity=15, you only want the two below. What about 6? or 19 etc? What are the conditions on which you decide to go for only ones below the quantity or ones above it? And how many below the quantity will you permit, or how many above it?

|||

can u explain more clearly...

|||

Mikesdotnetting:

If you enter Quantity=15, you only want the two below.

No.You are wrong way.See belove If I enter qty 15 that means it should return belove price 6 of qty 10and above price 4 of qty 20(between qty 10 and 20)

ID qty1 price1 qty2 price2 qty3 price3 qty4 price4

1 1 10 5 8 10 6 20 4

|||

murthysrn:

can u explain more clearly...

Look at this

ID qty1 price1 qty2 price2 qty3 price3 qty4 price4

1 1 10 5 8 10 6 20 4

I want the nearest above and belove prices and qty.

If Enter qty=9 then output should be like this

minQty minPrice MaxQty MaxPrice

5 8 10 6

Got It?


Need some with query

Hi, I need some help formulating a query. Below is an example records.
What I am trying to do is to come up with a query that will tell me which
record has a position_startdate that is less than position_enddate from the
record above.
ID EMP_ID POSITION POSITION_STARTDATE POSITION_ENDDATE
-- -- -- -- --
--
18 18 SALES 1/21/03
6/5/04
25 18 SALES MGR 6/5/04
12/28/04
31 18 DEPT SUP 10/18/04
8/8/05
45 18 STORE MGR 8/8/05
null
In this example, the query should pickup ID = 31 since 10/18/04 is less than
the previous postion_enddate which is 12/28/04.
Also, I am running this query with tons or employees.
I am currently working on this and thought that I might post it and get a
quick response back.
Thanks,
JB..Rick Shaw wrote:

> Below is an example
> records. What I am trying to do is to come up with a query that will
> tell me which record has a position_startdate that is less than
> position_enddate from the record above.
You should provide more information to get a better answer but I think
this should do it, assuming that when you say 'record above' you mean a
record with a lower ID.
Select T1.* from Table T1 where T1.Position_StartDate < (select top 1
T2.Position_EndDate from Table T2 where T2.ID < T1.ID order by T2.ID
Desc)
HTH,
Stijn Verrept.|||Stijn Verrept wrote:

> Rick Shaw wrote:
>
> You should provide more information to get a better answer but I think
> this should do it, assuming that when you say 'record above' you mean
> a record with a lower ID.
> Select T1.* from Table T1 where T1.Position_StartDate < (select top 1
> T2.Position_EndDate from Table T2 where T2.ID < T1.ID order by T2.ID
> Desc)
Maybe
Select T1.* from Table T1 where T1.Position_StartDate < (select top 1
T2.Position_EndDate from Table T2 where T2.ID < T1.ID and T1.Emp_ID =
T2.Emp_ID order by T2.ID
Desc)
is better, depends if you need to compare it with the same Emp_ID or not
Kind regards,
Stijn Verrept.|||Thanks Stijn. It worked great.
Thanks again for the hand.
Rick..
"Stijn Verrept" <stjin@.entrysoft.com> wrote in message
news:v7KdnRH9lLMwlRjenZ2dnUVZ8qudnZ2d@.sc
arlet.biz...
> Stijn Verrept wrote:
>
> Maybe
> Select T1.* from Table T1 where T1.Position_StartDate < (select top 1
> T2.Position_EndDate from Table T2 where T2.ID < T1.ID and T1.Emp_ID =
> T2.Emp_ID order by T2.ID
> Desc)
> is better, depends if you need to compare it with the same Emp_ID or not
> --
> Kind regards,
> Stijn Verrept.

Need some suggestion

I have a stored procedure to retrieve records from a database, each record contains the following fields: merchant_id, shop_id, shop_sales_amount

each merchant can have several shops and the corresponding shop_sales_amount

the format of the report(detail section) is like this:

merchant1 $10000
merchant1-shop1 $5000
merchant1-shop2 $5000
merchant2 $1000
merchant2-shop1 $500
merchant2-shop2 $500
merchant3 $100
merchant3-shop1 $50
merchant3-shop2 $50
.....

merchant1 is group 1, merchant 2 is group 2, merchant 3 is group 3...etc, the amount following the merchant name is the total sales amount of each shop under the merchant, the ordering of the group is in descending order of this total sales amount...

It is quite complicated, seriously need some suggestions or hints, I am quite new to crystal reports. Hope someone could help me out, thanksSo you should create two Crystal report groups, Merchant (#1) and Shop (#2), an order on descending sales amount beneath these (using the record sort expert). Insert the sum of the sales amount grouped at the shop level (Insert Summary, field to summarize: shop_sales_amount; calculate this summary: Sum; summary location: group 2) and move from the group2 footer to the header.

Viola! (if I understand you correctly.)sql

Need some logic help

Trying to bind some data to a datalist for a report.

User selects an Industry from a dropdown list and then I dump all records for that industry. However in order to parse some of the record field values into names (I.E. from a 1 to the actual company name) for some records I have to read TABLE_ONE and for other records I might have to read TABLE_TWO depending on the value of FIELD_ONE.

If FIELD_ONE = "A" then I get the NAME from TABLE_ONE.
If FIELD_ONE = "B" then I get the NAME from TABLE_TWO.
If FIELD_ONE = "C" then I get the NAME from TABLE_THREE.

I'm lost at how to get started on this. I thought about adding IF statements to my query but these won't work because I'm not passing in the value of FIELD_ONE ahead of time - it's part of the query. So I thought maybe I could do a pre-read and store all FIELD_ONE values in an ArrayList and pass these in as parameters, but the stored proc is only being called once - so that won't work.

Any thoughts on how I can do this?I can think of a couple of ways to accomplish this, but the most elegant involves using right outer joins and the COALESE function. COALESE is a function that returns the first non-null expression from a list of parameters. So the SELECT statement would be something like the following

SELECT COALESE(TABLE_ONE.NAME, TABLE_TWO.NAME, TABLE_THREE.NAME)
FROM TABLE RIGHT OUTER JOIN TABLE_ONE ON (TABLE.FIELD = TABLE_ONE.KEY AND TABLE.FIELD_ONE = 'A')
RIGHT OUTER JOIN TABLE_TWO ON (TABLE.FIELD = TABLE_TWO.KEY AND TABLE.FIELD_ONE = 'B')
RIGHT OUTER JOIN TABLE_THREE ON (TABLE.FIELD = TABLE_THREE.KEY AND TABLE.FIELD_ONE = 'C')

The returned field will contain whichever value is not null, the one that is appropriate depending on the value of FIELD_ONE.

HTH|||Am I understanding that the lookup values are in different tables. If so then you'd be doing conditional joins which I don't think is possible. Assuming you can't change the table structure around, I would create a query that combines all the lookup information from Table_One, Table_two, and Table_three (and others) and then join this table to your original table. Something like:


Select YourMainTable.Field1, B.Name
From YourMainTable INNER JOIN
(
Select Field1,Name
From
(
Select Field1,Name FROM Table1
Union
Select Field1,Name FROM Table2
Union
Select Field1,Name FROM Table3
) A
) B ON(YourMainTable.Field1 = B.Field1)
sql

Wednesday, March 21, 2012

Need some help!

Hi All
I want to blow up the database. Say I have 10 records in a particular table
and I want to increase it to 100 records for performance testing purposes. I
s
there a way to do it in SQL Server?
Thank you
Viccu.Viccu
create table #test (id int not null identity(1,1))
declare @.i int
set @.i=1
while @.i<=100
begin
insert #test default values
set @.i=@.i+1
end
select * from #test
"Viccu" <Viccu@.discussions.microsoft.com> wrote in message
news:0324B0FE-8D59-4755-A736-4FCA8D844EF3@.microsoft.com...
> Hi All
> I want to blow up the database. Say I have 10 records in a particular
> table
> and I want to increase it to 100 records for performance testing purposes.
> Is
> there a way to do it in SQL Server?
> Thank you
> Viccu.|||How about that. In answering your question I grabbed a function that was
posted to this newsgroup by Peter Larson on 5/10/2006 @. 4:13AM (within
microsoft.public.sqlserver.programming there are 12 posts between yours and
his).
Anyway...
--Lets pretend this is your table:
create table #foo (col1 int identity(1,1), col2 varchar(10), col3 datetime)
go
--and here is your 10 rows of data
insert into #foo (col2, col3) values ('test 1', '1/1/2006')
insert into #foo (col2, col3) values ('test 2', '2/1/2006')
insert into #foo (col2, col3) values ('test 3', '1/3/2006')
insert into #foo (col2, col3) values ('test 4', '1/4/2006')
insert into #foo (col2, col3) values ('test 5', '5/1/2006')
insert into #foo (col2, col3) values ('test 6', '1/6/2006')
insert into #foo (col2, col3) values ('test 7', '1/7/2006')
insert into #foo (col2, col3) values ('test 8', '8/1/2006')
insert into #foo (col2, col3) values ('test 9', '1/9/2006')
insert into #foo (col2, col3) values ('test 10', '10/1/2006')
--Peter Larson's function:
CREATE FUNCTION dbo.fnSeqNumbers
(
@.LowLimit INT,
@.HighLimit INT
)
RETURNS @.Values TABLE
(
Value INT
)
AS
BEGIN
DECLARE @.Temp INT
IF @.LowLimit > @.HighLimit
SELECT @.Temp = @.LowLimit,
@.LowLimit = @.HighLimit,
@.HighLimit = @.Temp
INSERT @.Values VALUES (@.LowLimit)
WHILE @.@.ROWCOUNT > 0
INSERT @.Values
SELECT n.Value + t.Items
FROM @.Values n
CROSS JOIN (
SELECT COUNT(*) Items
FROM @.Values
) t
WHERE n.Value + t.Items <= @.HighLimit
RETURN
END
go
-- showing you the results from the function:
--select * from dbo.fnSeqNumbers(1,10)
--this returns 100 rows
select a.col2 + ' ' + LTRIM(STR(b.Value)), a.col3 From #foo a
cross join dbo.fnSeqNumbers(1,10) b
order by a.col2
--...but you already have 10 in your table so lets only insert 90 rows
insert into #foo (col2, col3)
select a.col2 + ' ' + LTRIM(STR(b.Value)), a.col3 From #foo a
cross join dbo.fnSeqNumbers(1,9) b
order by a.col2
select @.@.rowcount
--look at your "new" data:
select * From #foo
This solution assumes that you have an identity value as your primary key.
If that is not the case in your table but your primary key is a number you
should be able to convert the number to a string, concatinate the value from
the function, and convert it back to an int that could be used as your
primary key. Hopefully this example gives you a few ideas and points you in
a direction where you can figure out a solution.
Keith Kratochvil
"Viccu" <Viccu@.discussions.microsoft.com> wrote in message
news:0324B0FE-8D59-4755-A736-4FCA8D844EF3@.microsoft.com...
> Hi All
> I want to blow up the database. Say I have 10 records in a particular
> table
> and I want to increase it to 100 records for performance testing purposes.
> Is
> there a way to do it in SQL Server?
> Thank you
> Viccu.|||Thanks much.
"Uri Dimant" wrote:

> Viccu
> create table #test (id int not null identity(1,1))
> declare @.i int
> set @.i=1
> while @.i<=100
> begin
> insert #test default values
> set @.i=@.i+1
> end
> select * from #test
>
> "Viccu" <Viccu@.discussions.microsoft.com> wrote in message
> news:0324B0FE-8D59-4755-A736-4FCA8D844EF3@.microsoft.com...
>
>|||Thank you so much.
"Keith Kratochvil" wrote:

> How about that. In answering your question I grabbed a function that was
> posted to this newsgroup by Peter Larson on 5/10/2006 @. 4:13AM (within
> microsoft.public.sqlserver.programming there are 12 posts between yours an
d
> his).
> Anyway...
> --Lets pretend this is your table:
> create table #foo (col1 int identity(1,1), col2 varchar(10), col3 datetime
)
> go
> --and here is your 10 rows of data
> insert into #foo (col2, col3) values ('test 1', '1/1/2006')
> insert into #foo (col2, col3) values ('test 2', '2/1/2006')
> insert into #foo (col2, col3) values ('test 3', '1/3/2006')
> insert into #foo (col2, col3) values ('test 4', '1/4/2006')
> insert into #foo (col2, col3) values ('test 5', '5/1/2006')
> insert into #foo (col2, col3) values ('test 6', '1/6/2006')
> insert into #foo (col2, col3) values ('test 7', '1/7/2006')
> insert into #foo (col2, col3) values ('test 8', '8/1/2006')
> insert into #foo (col2, col3) values ('test 9', '1/9/2006')
> insert into #foo (col2, col3) values ('test 10', '10/1/2006')
>
> --Peter Larson's function:
> CREATE FUNCTION dbo.fnSeqNumbers
> (
> @.LowLimit INT,
> @.HighLimit INT
> )
> RETURNS @.Values TABLE
> (
> Value INT
> )
> AS
> BEGIN
> DECLARE @.Temp INT
> IF @.LowLimit > @.HighLimit
> SELECT @.Temp = @.LowLimit,
> @.LowLimit = @.HighLimit,
> @.HighLimit = @.Temp
> INSERT @.Values VALUES (@.LowLimit)
> WHILE @.@.ROWCOUNT > 0
> INSERT @.Values
> SELECT n.Value + t.Items
> FROM @.Values n
> CROSS JOIN (
> SELECT COUNT(*) Items
> FROM @.Values
> ) t
> WHERE n.Value + t.Items <= @.HighLimit
> RETURN
> END
> go
> -- showing you the results from the function:
> --select * from dbo.fnSeqNumbers(1,10)
>
> --this returns 100 rows
> select a.col2 + ' ' + LTRIM(STR(b.Value)), a.col3 From #foo a
> cross join dbo.fnSeqNumbers(1,10) b
> order by a.col2
>
> --...but you already have 10 in your table so lets only insert 90 rows
>
> insert into #foo (col2, col3)
> select a.col2 + ' ' + LTRIM(STR(b.Value)), a.col3 From #foo a
> cross join dbo.fnSeqNumbers(1,9) b
> order by a.col2
> select @.@.rowcount
>
> --look at your "new" data:
>
> select * From #foo
>
> This solution assumes that you have an identity value as your primary key.
> If that is not the case in your table but your primary key is a number you
> should be able to convert the number to a string, concatinate the value fr
om
> the function, and convert it back to an int that could be used as your
> primary key. Hopefully this example gives you a few ideas and points you
in
> a direction where you can figure out a solution.
> --
> Keith Kratochvil
>
> "Viccu" <Viccu@.discussions.microsoft.com> wrote in message
> news:0324B0FE-8D59-4755-A736-4FCA8D844EF3@.microsoft.com...
>
>|||google up "generate test data"|||Thank you.Because of the foreign key constraints,say one of my tables has a
value that should
correspond to the value in the other table. How would I include that
particular value
in the query given by you?
insert into #foo (col2, col3)
select a.col2 + ' ' + LTRIM(STR(b.Value)), a.col3 From #foo a
cross join dbo.fnSeqNumbers(1,9) b
order by a.col2
"Keith Kratochvil" wrote:

> How about that. In answering your question I grabbed a function that was
> posted to this newsgroup by Peter Larson on 5/10/2006 @. 4:13AM (within
> microsoft.public.sqlserver.programming there are 12 posts between yours an
d
> his).
> Anyway...
> --Lets pretend this is your table:
> create table #foo (col1 int identity(1,1), col2 varchar(10), col3 datetime
)
> go
> --and here is your 10 rows of data
> insert into #foo (col2, col3) values ('test 1', '1/1/2006')
> insert into #foo (col2, col3) values ('test 2', '2/1/2006')
> insert into #foo (col2, col3) values ('test 3', '1/3/2006')
> insert into #foo (col2, col3) values ('test 4', '1/4/2006')
> insert into #foo (col2, col3) values ('test 5', '5/1/2006')
> insert into #foo (col2, col3) values ('test 6', '1/6/2006')
> insert into #foo (col2, col3) values ('test 7', '1/7/2006')
> insert into #foo (col2, col3) values ('test 8', '8/1/2006')
> insert into #foo (col2, col3) values ('test 9', '1/9/2006')
> insert into #foo (col2, col3) values ('test 10', '10/1/2006')
>
> --Peter Larson's function:
> CREATE FUNCTION dbo.fnSeqNumbers
> (
> @.LowLimit INT,
> @.HighLimit INT
> )
> RETURNS @.Values TABLE
> (
> Value INT
> )
> AS
> BEGIN
> DECLARE @.Temp INT
> IF @.LowLimit > @.HighLimit
> SELECT @.Temp = @.LowLimit,
> @.LowLimit = @.HighLimit,
> @.HighLimit = @.Temp
> INSERT @.Values VALUES (@.LowLimit)
> WHILE @.@.ROWCOUNT > 0
> INSERT @.Values
> SELECT n.Value + t.Items
> FROM @.Values n
> CROSS JOIN (
> SELECT COUNT(*) Items
> FROM @.Values
> ) t
> WHERE n.Value + t.Items <= @.HighLimit
> RETURN
> END
> go
> -- showing you the results from the function:
> --select * from dbo.fnSeqNumbers(1,10)
>
> --this returns 100 rows
> select a.col2 + ' ' + LTRIM(STR(b.Value)), a.col3 From #foo a
> cross join dbo.fnSeqNumbers(1,10) b
> order by a.col2
>
> --...but you already have 10 in your table so lets only insert 90 rows
>
> insert into #foo (col2, col3)
> select a.col2 + ' ' + LTRIM(STR(b.Value)), a.col3 From #foo a
> cross join dbo.fnSeqNumbers(1,9) b
> order by a.col2
> select @.@.rowcount
>
> --look at your "new" data:
>
> select * From #foo
>
> This solution assumes that you have an identity value as your primary key.
> If that is not the case in your table but your primary key is a number you
> should be able to convert the number to a string, concatinate the value fr
om
> the function, and convert it back to an int that could be used as your
> primary key. Hopefully this example gives you a few ideas and points you
in
> a direction where you can figure out a solution.
> --
> Keith Kratochvil
>
> "Viccu" <Viccu@.discussions.microsoft.com> wrote in message
> news:0324B0FE-8D59-4755-A736-4FCA8D844EF3@.microsoft.com...
>
>|||You could hardcode a single value within the select, modify the function to
return an additional column that has "random" FK values passed out of it or
you could just use (re-use) the foreign key data that you already have in
your table (#foo in my example). You probably want to load all the columns
when you insert data...just make sure that you query your FK column from
your base table when joining to the function.
Keith Kratochvil
"Viccu" <Viccu@.discussions.microsoft.com> wrote in message
news:D11F6AF9-11D2-43FB-AF0D-40726220E012@.microsoft.com...
> Thank you.Because of the foreign key constraints,say one of my tables has
> a
> value that should
> correspond to the value in the other table. How would I include that
> particular value
> in the query given by you?
> insert into #foo (col2, col3)
> select a.col2 + ' ' + LTRIM(STR(b.Value)), a.col3 From #foo a
> cross join dbo.fnSeqNumbers(1,9) b
> order by a.col2sql

Need some help in searching

Dear ASP.NET

How can I find records that contain a STRING from some (more than one) other fields ?

for example, I have:

Name_First = "aaa"
Name_Middle = "bbb"
Name_Last = "ccc"

Key_Words = "aaa,bbb,ccc"
(includes all values - comma separated)

How can I do the SELECT so that when I search for "bbb" on Key_Words I will get my record ?

Should I use "LIKE %aaa%" or something like this ?
(should I keep the comma separators ?)

Thanks in advance, Yovav.You can use like % for sure. Generally when I have searching functions where a user can enter one or more fields

I apppend each field in the SQL string as I build it. So for example mine may look something like the following:

DECLARE @.SQLWHERE varchar(1000)
SET @.SQLWHERE = ''

IF @.FirstName IS NOT NULL
SELECT @.SQLWHERE = ' WHERE FirstName ' + ' LIKE ''' + '%' + @.FirstName + '%'''

IF @.LastName IS NOT NULL
BEGIN
IF @.SQLWHERE = ''
SELECT @.SQLWHERE = @.SQLWHERE + ' WHERE P.LastName ' + ' LIKE ''' + '%' +
@.LastName + '%'''
ELSE
SELECT @.SQLWHERE = @.SQLWHERE + ' AND P.LastName ' + ' LIKE ''' + '%' + @.LastName + '%'''
END

And you can keep doing that type of logic for as many as you would like,

Another option is not to include any "%" at all and then indicate on your textboxes where users search that they can enter a * or % for like searches.

Just food for thought.|||I doing this search on 6 NTEXT fields...
so I thought maybe it will be faster if I do it on one field that has the content of the all 6...

what do U think ?

+
How should I write it ?
"SELECT * FROM X WHERE Key_Words LIKE %'" & SearchString & "'%" ?|||' SELECT * FROM X WHERE FirstName ' + ' LIKE ''' + '%' + @.FirstName + '%'''
.LastName ' + ' LIKE ''' + '%' + @.LastName + '%'''

ANd keep appending for each additional field until you have all six included.

If this is a stored procedure assign your string to variable and then at the end
call exec yourVarialbename

For example

EXEC (@.SQLStatement)

Monday, March 12, 2012

Need records forthe last month

I need to retrieve records that are posted within the last month and I've
tried variations of below, but do not get all the desired result. I either
get records outside the range or not all the records I should. Posted is
Date1 below.
select convert(char,date1,101)as date1,convert(char,date2,101)as date2 from
table1 WHERE DATEDIFF( month, date1 , GETDATE() ) <=1
select convert(char,date1,101)as date1,convert(char,date2,101)as date2 from
table1 where date1 <= dateadd(month, -1, getdate())
It seems it should be very simple, but I haven't found the satisfactory
result.
I've been spending a lot of time on this and would appreciate some ideas.You don't explain exactly what is wrong with the result sets, but I'll
hazard a guess. GETDATE() returns both a date and a time part. So DateDiff
and date add will retain these, normally this is the desired operation but
in your case, I'd guess that you want all the rows in the last month, that
is everything after midnight (12:00am) on the given day. I'd suggest that
you do this like this...
select
convert(char,date1,101)as date1, convert(char,date2,101) as date2
from table1
where date1 <= dateadd(month, -1, dateadd( day, datediff( day, 0,
getdate() ), 0 ) )
It's like your second attempt, but with one difference, the way that getdate
is read.
The code dateadd(day, datediff( day, 0, getdate()),0) will perform a
GetDate() which is effectivly now, then strip off the time part to return
12:00am. Will return all rows which were returned in the last month, but
also including anything from the entire day of the first day in the range.
Regards
Colin Dawson
www.cjdawson.com
"SK" <SK@.discussions.microsoft.com> wrote in message
news:644FB09F-2EA2-434C-B4DC-D5BE6E46936A@.microsoft.com...
>I need to retrieve records that are posted within the last month and I've
> tried variations of below, but do not get all the desired result. I
> either
> get records outside the range or not all the records I should. Posted is
> Date1 below.
> select convert(char,date1,101)as date1,convert(char,date2,101)as date2
> from
> table1 WHERE DATEDIFF( month, date1 , GETDATE() ) <=1
>
> select convert(char,date1,101)as date1,convert(char,date2,101)as date2
> from
> table1 where date1 <= dateadd(month, -1, getdate())
> It seems it should be very simple, but I haven't found the satisfactory
> result.
> I've been spending a lot of time on this and would appreciate some ideas.
>
>|||Thank you so much for answering on a Saturday.
Yes, I wanted all the dates within the last month. After spending all day
on it and getting very , I finally found something that seems to
work. I created a date table with sample dates and compared very closely.
It was never quite accurate. I tried the code, but it returns records from
2005, which is a problem I was having also.
But, finally this seems to work.
select convert(char,date1,1) as date1
from table1
where date1 <= getdate() and date1 >=
convert(char,dateadd(month,-1,getdate()),1)
Thanks again,
SK
"Colin Dawson" wrote:

> You don't explain exactly what is wrong with the result sets, but I'll
> hazard a guess. GETDATE() returns both a date and a time part. So DateDi
ff
> and date add will retain these, normally this is the desired operation but
> in your case, I'd guess that you want all the rows in the last month, that
> is everything after midnight (12:00am) on the given day. I'd suggest tha
t
> you do this like this...
>
> select
> convert(char,date1,101)as date1, convert(char,date2,101) as date2
> from table1
> where date1 <= dateadd(month, -1, dateadd( day, datediff( day, 0,
> getdate() ), 0 ) )
> It's like your second attempt, but with one difference, the way that getda
te
> is read.
> The code dateadd(day, datediff( day, 0, getdate()),0) will perform a
> GetDate() which is effectivly now, then strip off the time part to return
> 12:00am. Will return all rows which were returned in the last month, but
> also including anything from the entire day of the first day in the range.
> Regards
> Colin Dawson
> www.cjdawson.com
> "SK" <SK@.discussions.microsoft.com> wrote in message
> news:644FB09F-2EA2-434C-B4DC-D5BE6E46936A@.microsoft.com...
>
>

NEED Query to find apostrophes in table

I've tried everything I can think of to find all the records in a table column (lastname) that contain an apostrophe. I know they are there (O'Brian, D'Marcus, etc.) However, I keep getting syntax errors.
Could someone PLEASE help?!!
Thanks,
KarenSELECT *
FROM theTableWithTheUnspecifiedName
WHERE lastName LIKE '%''%'-PatP|||Either way

USE Northwind
GO

SET NOCOUNT ON
CREATE TABLE myTable99(Col1 varchar(80))
CREATE INDEX IX1 ON myTable99(Col1)
GO

INSERT INTO myTable99(Col1)
SELECT 'abc' UNION ALL
SELECT 'a''c' UNION ALL
SELECT 'xyz'
GO

SELECT *
FROM myTable99
WHERE LEN(Col1) <> LEN(REPLACE(Col1,CHAR(39),''))
GO

SELECT *
FROM myTable99
WHERE Col1 LIKE '%''%'
GO

SET NOCOUNT OFF
DROP TABLE myTable99
GO

...it's a scan. I wonder if one would be more effecient than the other though|||Works fine.

Many thanks!!!!!

Karen

Need Query help please...

hi...

i have the table like this,

Table Name : sample
Total Records : 500000 (Consider like this)

Sample Records:
------

id ---- name
======================
1 ----- AAA
2 ----- BBB
3 ----- CCC
2 ----- AAA
3 ----- AAA
4 ----- CCC
1 ----- BBB

i want to search based on the name, i need the id value which is must present
in the all the searching name.

i wrote the query like this... here i built the query dynamicaly.. if the search name is
increase...table self join is increase for each name... how to avoid this.. without
self join how to write the query....

My query :

Query1:
--
select a.*
from
sample a
inner join sample b on a.id=b.id
where (a.name like 'AAA' and b.name ='BBB');

Result:
---
1 ----- AAA
2 ----- BBB
2 ----- AAA
1 ----- BBB

This the result set for the above query.. but i need the unique id value.. if i
remove the duplicate.. the query will be slow...

Query2:
---
select a.*
from
sample a
inner join sample b on a.id=b.id
where (a.name like 'AA%' and b.name ='BB%');

Result:
---
1 ----- AAA
2 ----- BBB
2 ----- AAA
1 ----- BBB

This the result set for the above query.. but i need the unique id value.. if i
remove the duplicate.. the query will be slow...

But need to fine tune these query...

Is there any other simple way to get the result...?

How to avoid the self join to get the result...

Can u any one help me...?

Thanks & Regards,
S.Ashokkumar.Question : The IDs Are Not Unique ! Are They Supposed To Be ?

Could You Give A Bit More Information On What It Is Your Searching For.

If SELECT.....WHERE (a.name = 'AAA' AND b.name = 'BBB');

Then Why Not

If SELECT.....WHERE (a.name = 'AAA' AND b.name ='BBB' AND c.name = 'CCC' );

Note : If You Use LIKE, Then You Must Use Wildcards. Eg LIKE 'AA%'
If No Wildcards, Then I Think LIKE 'AAA' Is The Same As = 'AAA'

Friday, March 9, 2012

Need most recent record from views.

I'm working with a report that uses three views. There are duplicate records because the 'priority' which comes from one view has changed and SELECT DISTINCT sees it as a separate record. The users only want the latest record with the changed 'priority'. A second view contains an audit datetime stamp and a third view contains additional fields needed. Is it possible to get the MAX datetime from the second view, thereby getting the latest 'priority' from the linked views? I've tried to SELECT MAX(audit_datetime) and also coded it in the WHERE clause but SQL does not like that. I assume it's because there are a number of fields in the SELECT.could you please send us the query in order to check the code, it should be working as you say, but maybe the code has a syntax error.

Saturday, February 25, 2012

need help: new at store procedure

HI,
I want to create Store Procedure that Do:
I have 2 tables (A,B) and i want to know if theres records equal
between A.id1 in B.id2 or in B.id3
I want to call this Store Procedure from Asp (need to know how)
I work with SQL Server.
Regardsmoshe wrote:
> HI,
> I want to create Store Procedure that Do:
> I have 2 tables (A,B) and i want to know if theres records equal
> between A.id1 in B.id2 or in B.id3
> I want to call this Store Procedure from Asp (need to know how)
> I work with SQL Server.
> Regards
Create a SQL login and add the user to your database. Let's assume you call
the login "asplogin" with a password of "nigolpsa"
In Query Analyzer, run this script:
Create PROCEDURE CompareData AS
SET NOCOUNT ON
IF EXISTS (SELECT * FROM A INNER JOIN B ON A.id1=B.id2) OR
EXISTS (SELECT * FROM A INNER JOIN B ON A.id1=B.id3)
RETURN 1
ELSE
RETURN 2
go
GRANT EXECUTE ON CompareData TO asplogin
go
In ASP (I'm assuming you mean classic ASP since you did not specify
ASP.Net), follow the procedure described here to add the ADO type library to
your application's global.asa file :
http://www.aspfaq.com/show.asp?id=2112
Then create a page with this code (untested - there may be typos or syntax
errors. This should give you the idea. Look up the correct syntax in the ADO
reference at
http://msdn.microsoft.com/library/e...pireference.asp)
:
<%
dim cn, cmd
set cn=createobject("adodb.connection")
set cmd=createobject("adodb.command")
With cmd
.CommandType=adCmdStoredProc
.CommandText="CompareData"
set .ActiveConnection = cn
.Parameters.Append .CreateParameter("RETURN_VALUE", _
adInteger,adParamReturnValue)
end with
cn.Open "Provider=SQLOLEDB; " & _
"Data Source=YourServerName; " & _
"Initial Catalog=YourDatabaseName;" & _
"User ID=asplogin;Password=nigolpsa"
cmd.Execute
If cmd.Parameters(0) = 1 Then
Response.Write "Matching records exist"
Else
Response.Write "No matching records exist"
End if
cn.close: set cn=nothing
%>
HTH,
Bob Barrows
--
Microsoft MVP - ASP/ASP.NET
Please reply to the newsgroup. This email account is my spam trap so I
don't check it very often. If you must reply off-line, then remove the
"NO SPAM"

Monday, February 20, 2012

Need help writing search query

I am not very familiar with the syntax of MS SQL and I am trying to write a stored procedure which would do a search and return matching records.
This is what I need to achieve:
for instance I create a form with 4 text fields
- First Name
- Last Name
- Employee ID
- Date

I am interested in writing a stored procedure that would run a select query based on the input in the text fields
e.g.
- if the user enters First Name and the Last Name (leaving Employee ID and Date fields blank) query should be something like
select * from Employee where FirstName like @.FirstName and LastName like @.LastName
- or if the user enters only the Employee ID stored procedure should run a query similar to
select * from Employee where EmployeeID like @.EmployeeIDselect *
from Employee
where (FirstName like @.FirstName and LastName like @.LastName)
or
(EmployeeID like @.EmployeeID)|||Thanks for the your time blindman .. that was absolutely brilliant, shows you know your SQL :cool:
This query would sure work for the example I posted, but I was just wondering if I can give user more flexibility and allow him to enter lets say [partial first name (some string with wildcard characters) and partial ID] or [partial first name, last name and ID] or some such wierd combination. The query should adapt to the input and return result accordingly.
What is the best way to go about doing this, again thanks for any help I can get.
Thank you.
Have a great day.|||Yes.

You will need to add more complexity to your WHERE clause to accomplish the logic you want.

You will also need to use the LIKE operator if you want to allow wildcards.

You will also need to expect this query not to run very fast, if you include lots of logical operators and LIKE comparisons in your criteria...|||Since this is in a stored procedure you might use dynamic SQL to create the query on the fly and then execute it.

eg.

create x @.empid int, ...

declare @.sql varchar(200)

set @.sql = 'select * from Employee where '

if empid is not null set @.sql = @.sql & 'EmployeeID =' & @.empid

... etc etc

exec (@.sql)

...|||Thanks ejustuss and blindman, you guys were a tremendous help.
Since I am not very comfortable writing stored procedures this was my solution to the problem .. nothing ingenious but hey as long it works thats all I care about :D.
So I wrote this insanely strict stored procedure which would except user to input all the parameters (first name, last name, Employee ID, Date ... everything) and wrote a query something similar to this:
select * from Employee where FirstName like @.FirstName and LastName like @.LastName and EmployeeID like @.EmployeeID and ....
Since my stored procedure is not giving any flexibility to the user, I added flexibility on the client side in the web form code by replacing all fields left blank by the user with wildcard '%'. So if a user wanted to search by employee's first name, he would just enter the first name leaving other field blanks. These blank fields will be replaced with % and passed to the stored procedure.|||Not sure how effecient this is :

SELECT * FROM Employee
WHERE EmployeeID LIKE ISNULL('%' + @.EmployeeID + '%', EmployeeID)
AND FirstName LIKE ISNULL('%' + @.FirstName + '%', FirstName)
AND LAstName LIKE ISNULL('%' + @.LastName + '%', LastName)
AND DATEDIFF(Day, ISNULL(@.Date, Date), Date) = 0;|||Hey afx thanks for posting your version of the solution. I am sorry but I really did not understand the code you posted. Though your input was definetely useful since using ISNULL is by far a way better more efficient option :cool:
This is how I would use ISNULL

SELECT * FROM Employee
WHERE EmployeeID LIKE ISNULL( @.EmployeeID, '%')
AND FirstName LIKE ISNULL( @.FirstName, '%')
AND LAstName LIKE ISNULL( @.LastName, '%')

Thank you again for the input and effort :) :)|||Hi all,

I need help on building query statement. below is my table called inventory.

idx fabidx coloridx qty isReserved
1 1 1 15 Y
2 1 2 20
3 1 1 10
4 1 1 25 Y
5 1 2 23 Y
6 1 3 26
This is the output that i'm expecting.
fabidx coloridx qty isReserved
1 1 50 2
1 2 43 1
1 3 26 0
I need to get all distinct fabidx and coloridx, i need to get the sum of the distinct fabidx and coloridx, and i need to get the count of "Y" in the isReserved column of the distinct fabidx and coloridx.

Please help. Thanks.|||A simple aggregation query. Look up aggregation function in Books Online, and then post this as a new thread if you still need help.

Need help with UDF useage. Trying to get away without using cursor.

I have a Function (say X) that takes 2 parameters and returns back a table result of multiple records.

And I have a query (say Q) that return rows of 2 columns that I need to feed Function X.

They way I do it right now is I have a cursor that loops through the result of Query Q
and call Function X as I pass the 2 values the the function.

As Function X return with the result set, I load it into a temporary table.

At the end of the cursor processing, I query the temporary table to return the complete result set.

Is there a way do this without using a cursor?

Here is my Function X top part:

alter FUNCTION ReturnItem
(
@.tableName varchar(50),
@.ItemID int
)
returns @.returnTable table
(
ItemName varchar(50),
ItemValue varchar(50),
[Timestamp] datetime
)

JB..

You want to use the CROSS APPLY capability of SS2k5 to "apply" the rows of one table to a UDF. Here is an example:

CREATE TABLE QuerySource
(
c1 INT,
c2 INT
)

INSERT QuerySource VALUES (1,1)
INSERT QuerySource VALUES (2,3)
INSERT QuerySource VALUES (10,15)
INSERT QuerySource VALUES (16,13)

CREATE FUNCTION ReturnItem
(
@.p1 INT,
@.p2 int
)
returns @.returnTable table
(
AddResult int,
SubtractResult int,
TimesResult int,
DivideResult int
)
AS
BEGIN
INSERT @.returnTable SELECT @.p1+@.p2, @.p1-@.p2,@.p1*@.p2,@.p1/@.p2
RETURN
END

SELECT *
FROM QuerySource qs CROSS APPLY dbo.ReturnItem(qs.c1, qs.c2)

|||Hello. Thank you very much for you help. That is exactly what I wanted to do. I never knew such feature exist. Anyway, I was afraid that when the number of data being passed becomes really big, the cursor will slow things down hence, I have to find this solution.

Thank you again.

JB..