Showing posts with label thru. Show all posts
Showing posts with label thru. Show all posts

Wednesday, March 28, 2012

How do I loop thru a result set?

How do I loop thru a result set Without using a curosr?[1]
select @.key = min(key) from tab
while @.key is not null begin
...
select @.key = min(key) from tab where key > @.key
end

[2]
Define a function which does your dirty work and returns a result value
(even dummy)
Then
select dbo.fn_dirtywork(col1,col2,col3,col4,...) from tab

[3]
Don't.

"Andrew Young" <atyoung75@.yahoo.com> wrote in message
news:422d5636.0406280544.7f205a34@.posting.google.c om...
> How do I loop thru a result set Without using a curosr?|||On 28 Jun 2004 06:44:05 -0700, Andrew Young wrote:

>How do I loop thru a result set Without using a curosr?

Hi Andrew,

Mischa already gave some suggestions. I'd have put number three first (and
repeated it several times).

Seriously: why do you want to loop through a result set? Can you describe
the business need you're trying to solve? Set-based solutions tend to be
better and quicker and most problems CAN be solved with set-based SQL.

On the other hand, if you really must (or want to) loop through a result
set, why not use a cursor? That's SQL's standard instrument for looping
through a result set. Of course, you can find other ways to do the same,
but they'll probably be less efficient than a cursor (which is already
very inefficient!)

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||Andrew Young (atyoung75@.yahoo.com) writes:
> How do I loop thru a result set Without using a curosr?

I could a few more suggestions to Mischa's list, but I think I go with
his [3]. Then again, you should probably better clarify what your
real problem is. Maybe you are not iterating on the server, but in a
client?

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Here is my process:

I am pulling performance metrics for over a thousand servers, W2K,
W2K3, NT, RS6000, and AS400. This equates to about 50 to 100 million
rows of data in a 24 hour period. I have a SLA of 24 hours to provide
this data on a daily basis.

My process consists of pulling a comma delimited format file that I
'bulk insert', from a UNC path, into a temporary table. I then fire a
stored proc that reads thru the temp table and process the data.

The data file format is:
hostname,application,application_instance,paramete r,timesatmp,data_point

My database consists of a hostname table, application table, instance
table, parameter table, agregatted data table and a raw data table.

All have primary key and constraints except for raw data table. My
first stored proc determines the existence of the hostname, app,
inst,param, and if they don't exist it adds them to the respected
table and then dumps the raw into the raw data table with application
and parameter keys to be used later. This proc will fire and process
several time in a minute processing inbound data files.

Every six hours a aggregation proc fires and move the data from the
raw table into the agg table and then deletes the raw stuff.

I hope this explains my need for looping. Any advise would be much
appreciated.|||Andrew Young (atyoung75@.yahoo.com) writes:
> My process consists of pulling a comma delimited format file that I
> 'bulk insert', from a UNC path, into a temporary table. I then fire a
> stored proc that reads thru the temp table and process the data.
> The data file format is:
> hostname,application,application_instance,paramete r,timesatmp,data_point
> My database consists of a hostname table, application table, instance
> table, parameter table, agregatted data table and a raw data table.
> All have primary key and constraints except for raw data table. My
> first stored proc determines the existence of the hostname, app,
> inst,param, and if they don't exist it adds them to the respected
> table and then dumps the raw into the raw data table with application
> and parameter keys to be used later. This proc will fire and process
> several time in a minute processing inbound data files.
> Every six hours a aggregation proc fires and move the data from the
> raw table into the agg table and then deletes the raw stuff.
> I hope this explains my need for looping.

Not really. That is, I don't really see where the loop comes in.

When you get that data in, you would do

INSERT hostnames (hostname)
SELECT DISTINCT hostname
FROM rawdata r
WHERE NOT EXISTS (SELECT *
FROM hostname h
WHERE r.hostname = h.hostname)

and the similar for the other tables.

The aggregation should be possible to carry out with set-based statements.

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

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

How do I loop thru a record set in a stored procedure?

Below is a stored procedure that designed to populate a drop down menu system on a website. It works fine as long as the 'id's in the first select start at 1 and are sequential. It fails to grab all the sub tables if the ids are not sequential. So, how do I structure the loop so that the WHERE clause uses not the loop iterator, but rather, the ids from the first Select statement.

Alternatively, is there a more elgant approach that will return the same set of recordsets?

Any help would be much appreciated
Thanks

ALTER PROCEDURE dbo.OPA_GetMenuItems
AS
Declare @.i tinyint ,
@.tc tinyint
Set @.i = 1

/* Select for top level menu items*/

SELECT id, label, url, sort
FROM mainNav
ORDER BY sort

Set @.tc = @.@.rowcount

while @.i <= @.tc

begin
Set @.i = (@.i + 1)

/* Select for submenu items*/
SELECT id, label, url, sort, mainNavId
FROM SubNav
WHERE (mainNavId = @.i)
ORDER BY mainNavId, sort
end

RETURNI'm thinking that what you really want to do is perform a join and then handle the presentation stuff on the client side. I can't think of any valid reason why you would want to write your stored proc in the manner you have outlined above.

SELECT
m.id as MainID,
m.label as MainLabel,
m.url as MainUrl,
m.sort as MainSort,
s.id,
s.label,
s.url,
s.sort
FROM
mainNav m inner join SubNav s
ORDER BY
m.sort,
s.sort

Regards,

hmscott|||Yeah, you definitely seem hazy on the SQL concept. What is the output format you want for your dropdown list? Give us a sample of the data you want to display.|||The objective is to return a .Net dataset that contains a series of recordsets . The first recordset is the items contained in the top bar of the menu site. The subsequest recordsets contain the submenus for each item in the top menu.

The challenge is that it's not a simple binding issue once the data is returned from the stored proc. Some items in the top bar may not have a submenu and therefore require different html and javascript.

Inorder to render a lightweight, css-based (and W3C compliant) menu system, I need to determine at runtime which items have submenus and which don't

- items with no submenu need to have code that only closes other menus
- items with submenus need to have the closing code and also code to open there respective submenu.

A working (static) example would be something like http://peelcas.org/home/index.aspx

In order to pull this off, I have a c# routine that loops thru the dataset and renders the html.

Here's the c# code

///////////////////////////
// build global menu system
///////////////////////////

string sqlConnstring = ConfigurationManager.ConnectionStrings["sqlConnString"].ConnectionString;
DataSet NavData = new DataSet();
NavData = SqlHelper.ExecuteDataset(sqlConnstring, CommandType.StoredProcedure, "OPA_GetMenuItems");
//Response.Write(NavData.Tables.Count.ToString());

int i = 1; // counter for looping thru tables collection
int tc = NavData.Tables.Count - 1;
System.Text.StringBuilder sbNavLinks = new StringBuilder();
System.Text.StringBuilder sbSubLinks = new StringBuilder();
string url;
//string webSectionName;
string label;
string anchorId;
string menuId;

// build main nav bar
sbNavLinks.Append("<div id=\"navBar\"><ul>\r");
while (i < tc)
{
label = NavData.Tables[0].Rows[i].ItemArray[1].ToString();
anchorId = NavData.Tables[0].Rows[i].ItemArray[3].ToString();
url = NavData.Tables[0].Rows[i].ItemArray[2].ToString();

// no submenu items for this web section therefore...
// ...create main nav bar link with global menu closing javascript only
if (NavData.Tables[i].Rows.Count == 0)
{
sbNavLinks.Append("<li><a href=\""
+ url + "\" onmouseover=\"P7_autoLayers(0);\">"
+ label + "</a></li>\r");
}
// has submenu items therefore...
// ...create main navbar link with submenu opening javascript
else
{
// main navbar link
sbNavLinks.Append("<li><a href=\""
+ url + "\""
+ " id=\"Anchor" + anchorId + "\""
+ " onmouseover=\"P7_autoLayers(0,'subMenu" + anchorId + "');"
+ "P7_Snap('Anchor" + anchorId + "','subMenu" + anchorId + "',0,24);"
+ "\">"
+ label + "</a></li>\r");
}
i++;
}
sbNavLinks.Append("</ul></div>\r");
navBar.Text = sbNavLinks.ToString();

// build submenus

int j = 0; // counter for looping thru rows in current table
int rc; // row count of current table
i = 1;
while (i < tc)
{
if (NavData.Tables[i].Rows.Count > 0)
{
// extract menu id for use in div id

menuId = NavData.Tables[i].Rows[0].ItemArray[4].ToString();
//Response.Write(webSectionSort);

sbSubLinks.Append("<div id=\"subMenu" + menuId + "\" style=\"position:absolute; z-index:" + menuId + "; visibility: hidden;\">\r");
sbSubLinks.Append(" <div class=\"subButton\">\r");
sbSubLinks.Append(" <ul>\r");

rc = NavData.Tables[i].Rows.Count -1;

while (j <= rc)
{
// extract data for this link
label = NavData.Tables[i].Rows[j].ItemArray[1].ToString();
url = NavData.Tables[i].Rows[j].ItemArray[0].ToString();

sbSubLinks.Append("<li><a href=\""
+ url + "\" class=\"subButton\">"
+ label + "</a></li>\r");
j++;
}

sbSubLinks.Append("</ul></div></div>\r\r");
}
i++;
j = 0;
}
subNavBar.Text = sbSubLinks.ToString();
NavData.Dispose();

Yes I too dislike all this looping business, but I don't have a way of binding and achieving the desired results...|||What about a left join, instead of an inner join. With a left join, you could easily determine the MainMenu items with no submenus (the submenu fields would be null).

You would still loop through it on the web server.

Alternatively, you could use the FOR XML clause to create an XML string (which you would have to wrap inside of xml tags to make compliant).

Regards,

hmscott|||I'm not a C coder. You need to give us the layout of the recordset that you want to get from the server. We can help you with that, and from there on its up to you.|||Thanks for the offer...

I think hmscott's suggestion of a Left Join might just work, so I will groove on that for a while. As much as you're not a C# guy, I'm not a Sql guy, so I often just need a nudge in the right directlon..

Thanks againsql

Monday, March 26, 2012

How do I install sqlcmd.exe in my SQL Server client

I have SQL Server 2000 client installed in my machine and I need to call stored procedures thru sqlcmd utility. When I tried using this utility, I got an error message from command prompt sqlcmd command does not exist.

I have osql utility in my client version, but i need to have sqlcmd utility.

Please advice how do I install sqlcmd.exe in my SQL Server client?SQLCMD was introduced in SQL Server 2005. For SQL Server 200, you can either use the OSQL.exe or the ISQL.exe tool.

HTH, Jens K. Suessmeyer.

http://www.sqlserver2005.de