Showing posts with label record. Show all posts
Showing posts with label record. Show all posts

Friday, March 9, 2012

Needs Help With Creating a New Stored Procedure

I already know how you create a stored procedure to add information to a database or retrieve a value for one record. But I don't know how to create a stored procedure that will retrieve many records for a certain querystring value.

Here's my simple stored procedure to show one record:

CREATE PROCEDURE DisplayCity
(
@.CityID int
)
AS

SELECT City From City where CityID = @.CityID
GO

My code for displaying the City:

Sub ShowCity()

Dim strConnect As String

Dim objConnect As SqlConnection

Dim objCommand As New SqlCommand

Dim strCityID As String

Dim City As String

'Get connection string from Web.Config

strConnect = ConfigurationSettings.AppSettings("ConnectionString")

objConnect = New SqlConnection(strConnect)

objConnect.Open()

'Get incoming City ID

strCityID = request.params("CityID")

objCommand.Connection = objConnect

objCommand.CommandType = CommandType.StoredProcedure

objCommand.CommandText = "DisplayCity"

objCommand.Parameters.Add("@.CityID", CInt(strCityID))

'Display SubCategory

City = "" & objcommand.ExecuteScalar().ToString()

lblCity.Text = City

lblChosenCity.Text = City

objConnect.Close()

End Sub

Here's the code I'd like to get help with changing into a stored procedure:

Sub BindDataList()

Dim strConnect As String

Dim objConnect As New System.Data.SqlClient.SQLConnection

Dim objCommand As New System.Data.SqlClient.SQLCommand

Dim strSQL As String

Dim dtaAdvertiser As New System.Data.SqlClient.SQLDataAdapter()

Dim dtsAdvertiser As New DataSet()

Dim strCatID As String

Dim strCityID As String

Dim SubCategory As String

Dim SubCategoryID As String

Dim BusinessName As String

Dim City As String

'Get connection string from Web.Config

strConnect = ConfigurationSettings.AppSettings("ConnectionString")

objConnect = New System.Data.SqlClient.SQLConnection(strConnect)

objConnect.Open()

'Get incoming querystring values

strCatID = request.params("CatID")

strCityID = request.params("CityID")

'Start SQL statement

strSQL = "select * from Advertiser,AdvertiserSubCategory, Categories, SubCategories, County, City"

strSQL = strSQL & " where Advertiser.CategoryID=Categories.CategoryID"

strSQL = strSQL & " and Advertiser.AdvertiserID=AdvertiserSubCategory.AdvertiserID"

strSQL = strSQL & " and AdvertiserSubCategory.SubCategoryID=SubCategories.SubCategoryID"

strSQL = strSQL & " and Advertiser.CountyID=County.CountyID"

strSQL = strSQL & " and Advertiser.CityID=City.CityID"

strSQL = strSQL & " and AdvertiserSubCategory.SubCategoryID = '" & strCatID & "'"

strSQL = strSQL & " and Advertiser.CityID = '" & strCityID & "'"

strSQL = strSQL & " and Approve=1"

strSQL = strSQL & " Order By ListingType, BusinessName,City"

'Set the Command Object properties

objCommand.Connection = objConnect

objCommand.CommandType = CommandType.Text

objCommand.CommandText = strSQL

'Create a new DataAdapter object

dtaAdvertiser.SelectCommand = objCommand

'Get the data from the database and

'put it into a DataTable object named dttAdvertiser in the DataSet object

dtaAdvertiser.Fill(dtsAdvertiser, "dttAdvertiser")

'If no records were found in the category,

'display that message and don't bind the DataGrid

if dtsAdvertiser.Tables("dttAdvertiser").Rows.Count = 0 then

lblNoItemsFound.Visible = True

lblNoItemsFound.Text = "Sorry, no listings were found!"

else

'Set the DataSource property of the DataGrid

dtlAdvertiser.DataSource = dtsAdvertiser

'Set module level variable for page title display

BusinessName = dtsAdvertiser.Tables(0).Rows(0).Item("BusinessName")

SubCategory = dtsAdvertiser.Tables(0).Rows(0).Item("SubCategory")

SubCategoryID = dtsAdvertiser.Tables(0).Rows(0).Item("SubCategoryID")

City = dtsAdvertiser.Tables(0).Rows(0).Item("City")

'Bind all the controls on the page

dtlAdvertiser.DataBind()

end if

objCommand.ExecuteNonQuery()

'this is the way to close commands

objCommand.Connection.Close()

objConnect.Close()

End Sub

It's really no different. If I understand what you mean then you'd want the following stored procedure:

CREATE PROCEDURE DisplayCity
(
@.CatID Int,
@.CityID Int
)
AS

SELECT * from Advertiser,AdvertiserSubCategory, Categories, SubCategories, County, City
where Advertiser.CategoryID=Categories.CategoryID
and Advertiser.AdvertiserID=AdvertiserSubCategory.AdvertiserID
and AdvertiserSubCategory.SubCategoryID=SubCategories.SubCategoryID
and Advertiser.CountyID=County.CountyID
and Advertiser.CityID=City.CityID
and AdvertiserSubCategory.SubCategoryID = @.CatID
and Advertiser.CityID = @.CityID
and Approve=1
Order By ListingType, BusinessName,City

GO|||I actually need help with my Code for displaying the stored procedure and records. I only know how to retrieve one record using a stored procedure.|||Your original question was misleading, then :)

I'd recommend readingthese Microsoft tutorials on performing data access. There are many ways to loop through records and display data so find the one most suitable for you.|||

You would need to do a while statement. If you are using SQL Server then you can do your SQL DataReader. Just do a while loop and tell your code to keep reading until end of records and for each row add it to an array. Then you can bind thay array to a datagrid.

Wednesday, March 7, 2012

Needed help in Query

Hai

1. Is it possiable to delete a record from the parent table.It is
even ok to me , if it leads to the deletion of all the child tables .

2.I 've come across a situiation where the name of the table is to be
supplied by the variable in my sp ,like

@.t = 'table1'
select * from @.t -- it gives the error.

--actually i want "select * from table1" & in my sp i gave as

So i am forced to give the table name from the sub query.

how can i acheive this thru query where the table name has to be
supplied to the from clause from the sub query

With Thanks
Raghuraman.C"Raghuraman" <raghuraman_ace@.rediffmail.com> wrote in message
news:66c7bef8.0401152012.7e068064@.posting.google.c om...
> Hai
> 1. Is it possiable to delete a record from the parent table.It is
> even ok to me , if it leads to the deletion of all the child tables .
>
> 2.I 've come across a situiation where the name of the table is to be
> supplied by the variable in my sp ,like
>
> @.t = 'table1'
> select * from @.t -- it gives the error.
> --actually i want "select * from table1" & in my sp i gave as
> So i am forced to give the table name from the sub query.
> how can i acheive this thru query where the table name has to be
> supplied to the from clause from the sub query
> With Thanks
> Raghuraman.C

I'm not sure if I understand your questions completely, but I think this is
what you want:

1. If possible, you can declare your foreign keys with ON DELETE CASCADE
(see Books Online). Then when you delete a row from the parent table, any
child records will automatically be deleted also. If that isn't a good
solution in your situation, you can consider triggers, or doing all deletes
through a stored procedure which deletes rows from the tables in the correct
order.

2. See this link:

http://www.sommarskog.se/dynamic_sql.html

Simon|||Dear simon,

For the option 1.

I could not reach any word combinations like DELETE ON CASCADE for the
foriegn keys in the books on line in sqlserver 7.0. Are u telling with
SQLSERVER2000.

If so, what the way in sqlserver7.0

With regards
Raghu

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||Raghu Raman <raghuraman_ace@.rediffmail.com> wrote in message news:<400cd41a$0$70304$75868355@.news.frii.net>...
> Dear simon,
> For the option 1.
> I could not reach any word combinations like DELETE ON CASCADE for the
> foriegn keys in the books on line in sqlserver 7.0. Are u telling with
> SQLSERVER2000.
> If so, what the way in sqlserver7.0
> With regards
> Raghu
>
> *** Sent via Developersdex http://www.developersdex.com ***
> Don't just participate in USENET...get rewarded for it!

Yes, cascading DRI is only available in SQL2000. I should have
mentioned that, but please always state which version of MSSQL you're
using. In SQL7, you can either use triggers or stored procedures. If
you can ensure that your applications will always use a stored proc
for deletions, then it is probably an easier solution. But if you have
different applications/clients, and you can't be sure that they will
always use the proc, then a trigger is more reliable.

Simon|||Hai,

I did that cascading deletion using sproc..& it is nice

Thanks for concurrent reply

With Regards
Raghu

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||>> 1. Is it possible to delete a record [sic] from the parent table.
<<

Tables are not files; rows are not records; columns are not fields.
They are compltely different concepts! There are "referenced" and
"referencing" tables in SQL. That "parent" and "child" terminology
belongs to network DBMS models.

You can set up DRI actions that will cascade a deletion from a
referenced table to all the referencing tables.

>> 2.I 've come across a situiation where the name of the table is to
be
supplied by the variable in my stored procedure ... <<

NO! The short answer is use slow, proprietrary dynamic SQL to kludge
a query together on the fly with your table name in the FROM clause.

The right answer is never pass a table name as a parameter. You need
to understand the basic idea of a data model and what a table means in
implementing a data model. Go back to basics. What is a table? A
model of a set of entities or relationships. EACH TABLE SHOULD BE A
DIFFERENT KIND OF ENTITY. What having a generic procedure works
equally on automobiles, octopi or Britney Spear's discology is saying
that your applications a disaster of design.

1) This is dangerous because some user can insert pretty much whatever
they wish -- consider the string 'Foobar; DELETE FROM Foobar; SELECT *
FROM Floob' in your statement string.

2) It says that you have no idea what you are doing, so you are giving
control of the application to any user, present or future. Remember
the basics of Software Engineering? Modules need weak coupling and
strong cohesion, etc.

3) If you have tables with the same structure which represent the same
kind of entities, then your schema is not orthogonal. Look up what
Chris Date has to say about this design flaw.

4) You might have failed to tell the difference between data and
meta-data. The SQL engine has routines for that stuff and
applications do not work at that level, if you want to have any data
integrity.

Yes, you can write a program with dynamic SQL to kludge something like
this. it will last about a year in production and then your data
integrity is shot.

Saturday, February 25, 2012

Need to write value of session variable to SQL record

Each user who inserts a new SQL record from the FormView control needs to have their UserID in one of the fields of the record. I have the user ID stored in the Session("UserID") variable. I am having trouble finding the right way to get this done. I have tried using a hidden text box but I can't seem to assign the value. I have tried the Insert Parameters but that will not accept <%# Session("UserID") %> as a DefaultValue. Any ideas would be helpful. Thanks.

Try handling the ItemInserting event of your FormView where you can programmatically set the SqlDataSource.DefaultValue to your Session variable value. For example:

protected void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
{
SqlDataSource1.InsertParameters["UserID"].DefaultValue = Session["UserID"].ToString();
}|||Worked great with "(" instead of brackets "[". Thanks!|||I'm glad it worked out. My example was in C#. I guess you needed VB sample instead.|||You could of also created a SessionParameter and done it without any code at all.|||

Motley wrote:

You could of also created a SessionParameter and done it without any code at all.

Brilliant!!!

Monday, February 20, 2012

Need to update all but first record in group by

I'd like to use an UPDATE statement to set 'Y' and 'N' values to a flag
field in a table called SVCrossSales for each set of records keyed by
the CSNum field. The first record in each group would get a CSFlg
value of 'N' and the subsequent records would get a 'Y'. Here's a
sample of what the CSFlg values should end up being for each CSNum:
INum CSNum CSFlg
-- -- --
2 1 N
2 1 Y
2 1 Y
2 2 N
2 2 Y
2 3 N
2 3 Y
2 3 Y
Instead of using a cursor to cycle through each CSNum, I'd like to use
an UPDATE statement with an aggregate join. I can't think of anything
else except using TOP to pick out the first record in the set.
Obviously, if I can set the 'N' values for CSFlg, I would do a simple
UPDATE to set the 'Y' values for the rest of the records.
This UPDATE fails:
UPDATE
SVCrossSales
SET
CSFlg = 'N'
FROM
SVCrossSales
INNER JOIN (
SELECT TOP 1 CSNum
FROM SVCrossSales
WHERE INum = 2
GROUP BY CSNum) GroupedSales ON (
SVCrossSales.CSNum = GroupedSales.CSNum)
WHERE
SVCrossSales.INum = 2
What is the proper syntax to do my UPDATE?>> I'd like to use an UPDATE statement to set 'Y' and 'N' values to a flag
Since there is no column values that can uniquely identify a row, this is
logically impossible.
Since a well designed table is a set of rows, the concept of
first/second/last etc. does not really apply. In a relational database,
you'd identify a row using the key values, not by positional descriptions.
TOP 1 without ORDER BY clause relies on certain internal materialization of
values, and it is much better to have
Once you have the keys & constraints explicitly declared, you can formulate
an UPDATE statement along the lines of:
UPDATE SVCrossSales
SET CSFlg = 'N'
WHERE EXISTS ( SELECT *
FROM SVCrossSales s1
WHERE s1.INum = SVCrossSales .INum
AND <predicate involving keys> )
AND INum = 2 ;
Anith|||Anith, I'm not sure how a WHERE EXISTS will help. It returns a boolean
result (true or false). How can that help identify the first record of
each set of CSNums? I need something to pick out the records marked
with an x below and set the CSFlg = 'N':
INum CSNum CSFlg
-- -- --
x 2 1 N
2 1 Y
2 1 Y
x 2 2 N
2 2 Y
x 2 3 N
2 3 Y
2 3 Y|||Steve,
I am not sure if you have taken time to read what I wrote. Note that it is
impossible to accomplish what you are asking to do, since there is no
logical way of identify a row without a key.
Also, you have not posted you table structures & sample data (
www.aspfaq.com/5006 ). It is not clear whether the sample data you posted
includes all the columns in the table or not. It is not clear whether you
have keys and constraints in your table.
The UPDATE statement I posted include a correlation denoted as <predicate
involving keys>. This is the most critical part is solving your problem. If
you have no keys, all bets are off.
Anith|||Sorry...should have posted this to begin with...
DDL for the SVCrossSales table:
CREATE TABLE [dbo].[SVCrossSales] (
[INum] [int] NOT NULL ,
[SalesNum] [int] NOT NULL ,
[CSNum] [int] NULL ,
[CSFlg] [char] (1) NULL ,
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[SVCrossSales] WITH NOCHECK ADD
CONSTRAINT [PK_SVCrossSales] PRIMARY KEY CLUSTERED
(
[INum],
[SalesNum]
) ON [PRIMARY]
GO
The INum is an ID field used in various tables of ours. The SalesNum
field is like an indentity seed in that it's a unique value for each
record in the table. Together, with INum, it forms the primary key for
the SVCrossSales table. I have a stored procedure that updates the
CSNum and then cycles through a cursor to update the CSFlg for each set
of recods with the same CSNum.
Sample data:
INum SalesNum CSNum CSFlg
-- -- -- --
2 333898 13295 N
2 333899 13295 Y
2 334366 13295 Y
2 335567 13269 N
2 335578 13269 Y
2 335579 13269 Y
2 336120 13255 N
2 336121 13255 Y
2 336122 13255 Y
So, is there a way to use a single update to set the 'N' values?|||I should have also mentioned that the INum and SalesNum fields link to
a sales table (SVSales) where my stored procedure's logic figures out
which sales to group together and assign the next available CSNum to in
SVCrossSales. The last step in the sproc is to update the CSFlg.|||Based on the sample data you posted, if the CSFlag column already has the
values 'Y', then do:
UPDATE SVCrossSales
SET CSFlg = 'N'
WHERE NOT EXISTS ( SELECT *
FROM SVCrossSales s1
WHERE s1.INum = SVCrossSales.INum
AND s1.CSNum = SVCrossSales.CSNum
AND s1.SalesNum < SVCrossSales.SalesNum )
AND INum = 2 ;
If both the values 'Y' and 'N' are to be set, then do:
UPDATE SVCrossSales
SET CSFlg = CASE WHEN EXISTS ( SELECT *
FROM SVCrossSales s1
WHERE s1.INum = SVCrossSales.INum
AND s1.CSNum = SVCrossSales.CSNum
AND s1.SalesNum <
SVCrossSales.SalesNum )
THEN 'Y' ELSE 'N' END
WHERE INum = 2 ;
You can re-write both these statements using a maxima function, but this
should give you what you are looking for.
Anith|||I replaced the cursor logic for updating CSFlg with the UPDATE
statement above. It didn't work. Also, it more than doubled the
execution time of the sproc. I don't understand what the EXISTS
subquery does. Shouldn't there be something to select the top 1 record
for each group set of records with the same CSNum?|||>> I replaced the cursor logic for updating CSFlg with the UPDATE statement
You will have to expand on that. Here is the data before & after update
based on the sample data you posted.
-- Before update
SELECT * FROM SVCrossSales ORDER BY INum, CSNum DESC, SalesNum
INum SalesNum CSNum CSFlg
-- -- -- --
2 333898 13295 Y
2 333899 13295 Y
2 334366 13295 Y
2 335567 13269 Y
2 335578 13269 Y
2 335579 13269 Y
2 336120 13255 Y
2 336121 13255 Y
2 336122 13255 Y
-- Do the update
UPDATE SVCrossSales
SET CSFlg = 'N'
WHERE NOT EXISTS ( SELECT *
FROM SVCrossSales s1
WHERE s1.INum = SVCrossSales.INum
AND s1.CSNum = SVCrossSales.CSNum
AND s1.SalesNum < SVCrossSales.SalesNum )
AND INum = 2 ;
-- After update
SELECT * FROM SVCrossSales ORDER BY INum, CSNum DESC, SalesNum
INum SalesNum CSNum CSFlg
-- -- -- --
2 333898 13295 N
2 333899 13295 Y
2 334366 13295 Y
2 335567 13269 N
2 335578 13269 Y
2 335579 13269 Y
2 336120 13255 N
2 336121 13255 Y
2 336122 13255 Y
That might have something to do with the overall construction of the stored
procedure and suboptimal indexing.
Well, as I said, there are several ways you can derive the solution. In this
case, you can use TOP 1 as well like:
UPDATE SVCrossSales
SET CSFlg = 'N'
WHERE SalesNum = ( SELECT TOP 1 s1.SalesNum
FROM SVCrossSales s1
WHERE s1.INum = SVCrossSales.INum
AND s1.CSNum = SVCrossSales.CSNum
ORDER BY s1.SalesNum )
AND INum = 2 ;
Anith|||Hi There,
Let us See if this can help your cause
--
Update yourTable Set CSFlag = 'N' Where SalesNum In (Select
Min(SalesNum) From yourTable Group By INum,CSNum)
--
Please let me know if it worked for You.
INum SalesNum CSNum CSFlg
-- -- -- --
2 333898 13295 N
2 333899 13295 Y
2 334366 13295 Y
2 335567 13269 N
2 335578 13269 Y
2 335579 13269 Y
2 336120 13255 N
2 336121 13255 Y
2 336122 13255 Y
With Warm regards
Jatinder Singh