Transact SQL :: Stored Procedure For Total Count For New Users

Jul 14, 2015

I need to create a stored procedure for total count of the user's. If  User from front end  invites other user to use my tool, that user will be stored into a table name called "test",lets say it will be stored as"Invited 1 User(s)" or if he invites 2 users it will store into table as "Invited 2 User(s)."

But now we have changed the concept to get the ISID (name of the user)  and now when ever the user invites from the front end, the user who have invited should stored in two tables "test" and " test1" table .

After we get the data into test and test1 table i need the total count of a particular user from both tables test and test1.

if i invite a user , the name of the user is getting stored in both test and test1 tables.Now i want to get the count of a user from both tables which should be 1,but its showing 2.

Reason: Why i am considering the count from 2 tables is because before we were not tracking the usernames and we were storing the count in single test table.,but now we are tracking user names and storing them in both tables(test and test1).

Here is my sample  code:

I need to sum it up to get the total user's from both the table but I should get 1 instead of 2 

(select distinct COUNT(*) from dbo.test
where New_Values like  '%invited%'
and Created_By= 'sam'
(select distinct count (*)  from dbo.test1
where invited_by ='sam'

View 8 Replies


Running Total Count In Stored Procedure

Jul 20, 2005


View 1 Replies View Related

Transact SQL :: Total Count Of Table Rows

Sep 15, 2015

I have a question regarding the total count of the table rows

Select count (name) from test. Lets say I have got 200 count. And Select count (lastname) from test1.I have got 200.And this counts I should store it in "There are nn name items awaiting your attention and nn pending lastname's awaiting your approval".

So now I have to store the count in 'nn'.

View 5 Replies View Related

Transact SQL :: Adding Count Before And After A Specific Time Doesn't Match Total Number Of Records

Nov 19, 2015

If I just use a simple select statement, I find that I have 8286 records within a specified date range.

If I use the select statement to pull records that were created from 5pm and later and then add it to another select statement with records created before 5pm, I get a different count: 7521 + 756 = 8277

Is there something I am doing incorrectly in the following sql?

DECLARE @startdate date = '03-06-2015'
DECLARE @enddate date = '10-31-2015'
DECLARE @afterTime time = '17:00'
General_Count = (SELECT COUNT(*) as General FROM Unidata.CrumsTicket ct

[Code] ....

View 20 Replies View Related

Stored Procedure To Get All Users Or All Users Of A Specific Country

Apr 30, 2008

hi alli've got two tables called "webusers" (id, name, fk_country) and "countries" (id, name)
at the meantime, i've a search-page where i can fill a form to search users. in the dropdown to select the country i included an option which is called "all countries".
now the problem is: how can i make a stored procedure that makes a restriction to the fk_country depending on the submitted fk_country parameter?it should be something like
SELECT * FROM webusers(if @fk_country > 0, which is the value for "all countries"){    WHERE fk_country = @fk_country}
who has an idea how to solve this problem?

View 9 Replies View Related

Total Record Count - Pagination With Total Rows

Jul 26, 2013

My table contains 1000 records,

I need to know the total record count with the below paging query

SELECT EmpName,Place
FROM EmplyeeDetails ORDER BY Place

How to get?

View 2 Replies View Related

Transact SQL :: Fine Tune Procedure / Accessed By Multiple Users

Oct 13, 2015

i have a report that runs on a huge table rpt.AgentMeasures  , it has 10 months worth of data (150 million records as of today and will keep increasing).  i have pasted my proc below , the other tables that are joined to this huge table do not have more then 3k records.This report will be accessed by multiple users (expecting 20 ppl). as of now this reports runs for 5 mins if i pull for 1 month worth of data. if it is wise to use temp tables.

ALTER proc [rpt].[Get_Metrics]
@Medium Varchar(max),
@footPrint varchar(max),


View 10 Replies View Related

Conditional Total In Stored Procedure

Aug 11, 2006

Is there a simple way to do conditional totaling?

I have a table that has incremental values, so the maximum value is the current total, however on occassion the value is reset and the increment begins anew. What I need to do is get the total the maximum value each time it is reset.


Value Date
----- -----
12 1-1
14 1-2
100 1-8
35 1-10
50 1-12
5 1-15

the total would be 155 (100 + 50 + 5)

View 4 Replies View Related

Stored Procedure + Return Total Row Affected

Jul 7, 2004


I have a stored procedure which is used to remove record from database.
Is there anyway to get the total row deleted for each table?

CREATE PROCEDURE dbo.sp_company_delete
@Company_Id int,
@Sched int Output,
@Users int Output,
@Asset int Output,
@Fleet int Output

Begin Transaction delete_company
Select @Sched = COUNT(*) from Scheduler Where Company_id=@Company_Id
Delete From Scheduler Where Company_id=@Company_Id

Select @Users = COUNT(*) From Users Where Company_Id=@Company_Id
Delete From Users Where Company_Id=@Company_Id

Select @Asset = COUNT(*) From Asset Where Company_Id=@Company_Id
Delete From Asset Where Company_Id=@Company_Id
Delete From Fleet Where Company_Id=@Company_Id
Delete From Company Where Company_Id=@Company_Id
Commit Transaction delete_company

Basically I want to get the total row deleted for each table and put it inside output parameters.

I am doing a double job here, first I get the count, put into output parameter, then only I delete the record.

Is there any other way which is more efficient to do this?

I tried using
SET @Sched = Delete From Scheduler Where Company_id=@Company_Id
SET @Users = Delete From Users Where Company_Id=@Company_Id
But doesn't work.

Any suggestion is welcomed.
Thank you in advanced.

View 2 Replies View Related

Create Stored Procedure To Get Total Last 7 Day Sales For Each Day

Mar 13, 2015

Table name: ONIV
Date: DocDate
Sales: DocTotal

I want to populate a line graph which would show the 7 days of the week on X-Axis and the sale on the Y-Axis.

View 2 Replies View Related

Sql Count Using Stored Procedure Withing Stored Procedure

Apr 29, 2008

I have a stored procedure that among other things needs to get a total of hours worked. These hours are totaled by another stored procedure already. I would like to call the totaling stored procedure once for each user which required a loop sort of thing
for each user name in a temporary table (already done)
total = result from execute totaling stored procedure
Can you help with this

View 10 Replies View Related

Users Cannot View Stored Procedure Text

Apr 4, 2007

In SQL 2005 (we use Enterprise 64-bit SP2), the users cannot see thetext of the stored procedures, functions, etc.This is a production database, so I cannot give them rights to modifythem, but they need to be able to see what the procs are doing.I didn't have this problem in 2000 - how can I adjust the privilegesto allow them to view the contents of the Programmability objects?thanks for any insight!!Tracy

View 2 Replies View Related

Stored Procedure To Grant All Users Db_owner

Jul 20, 2005

I am trying to come up with a stored procedure to grant all usersdb_owner role (rather than have to manually check the users eachtime)Thanks in advance for your helpTY

View 1 Replies View Related

1 To 1, 1 To Many. Create One Stored Procedure For Crystal Reports(CR). For Any CR Users Also.

Jul 12, 2007

Situation: If possible, create one stored procedure for Crystal Reports(CR). For any CR users ou
there, looking for coding suggestion also. Thank you for your assistance.

Currently, CR has a header(Report Header) coming from 1 to 1 tables, there is a parameter
which is passed in, allowing it to retrieve one record for the header(report header or RH).

The CR then has 4 subreports in which each has its own stored procedure. This I believe happens
because the Report Header records relationship to the subreport is 1 to many. The 3 remaining
subreports relationship to the Report Header is also a 1 to many. The main problem is the
subreports is that there may or may not have any records based on this, the subreport is
suppressed within CR and thus there can be alot of unused white space on the 1st page and one
of the subreports prints on a 2nd page when it could have been on the 1st page.


Main Stored Procedure(sp)
RH Tables: aaa, bbb, ccc, ddd are 1 to 1 record tables and have a @xyz parameter.

Results of subreports and their associated procedure are varchar(8000) decriptions. Each line
should be counted in some manner in the stored procedure(sp) and then should be counted in CR
to avoid excess white space. To complicate matters subreport 2 to has font, bold, showbox but
can have different font sizes. These variations could cause different line space requirements.
Any ideas?

Each line should be counted in some manner in the stored procedure and then should be counted
in CR. There is a count of records for each the main stored procedure.

RH has 1 record to many records in subreport 1 with same @xyz parameter.
RH has 1 record to many records in subreport 2 with same @xyz parameter.
RH has 1 record to many records in subreport 3 with same @xyz parameter.
RH has 1 record to many reords in subreport 4 with same @xyz parameter.

Because of the relationships, its seems impossible to create one stored procedure which give
in one select statement with all the 1 to 1, 1 to many relationsips, as stated above. I thought
concatinating i.e. 3 records together and then parsing it out some how in CR, along with
utilizing the i.e. 3 record count to help count lines. Thought of some how creating a temporary
table matrix for 8pt - 28pt for line and spacing considerations.

View 1 Replies View Related

See Application Users (View Server State) Within A Stored Procedure

Mar 17, 2008

Hello, i have a problem regarding stored procedures and view server state.

I have an application with a lot of stored procedures, one of them checks data of the connected users.
In SQL 2000 i had no problem getting this information, but in SQL server 2005 i do.

my stored procedure looks like this:

ALTER PROCEDURE [dba].[applsp_GetConnectionInfo]


@DBName varchar(100)





DECLARE @sCollationMaster VARCHAR(128);

DECLARE @sSqlString VARCHAR(900);

-- Determine collation from master database because collation from master and ultimo database may differ

SELECT @sCollationMaster = CAST(databasepropertyex('master', 'Collation') AS VARCHAR);

SET @sSqlString =

'SELECT max(status) AS Status, max(isnull(SCISUSENAME, ''ULTIMOLOGIN'')) AS Login

, MAX(Rtrim(Rtrim(convert(varchar(255), nt_domain)) + nt_username)) AS NTUser

, max(Rtrim(hostname)) AS Host, MAX(Rtrim(program_name)) AS Program

FROM master.dbo.sysprocesses JOIN dba.SCONNECTIONINFO on SCISPID = CAST(spid AS VARCHAR)

AND ( SCISUSENAME = ISNULL(loginame, '''') COLLATE ' + @sCollationMaster + ' OR ISNULL(loginame, '''') = ''ULTIMOLOGIN'')

WHERE ...... AND DB_NAME(dbid) = ''' + @DBName + '''

GROUP BY hostprocess





I've granted view server state permissions to my user 'dba' which is the db_owner.
When i execute the query in the stored procedure seperatly as dba i get all the info i need, but when i execute the stored procedure i don't see anything.

I seem to have the same problem with sp_who2
Executing it gives me information about everyone but when i put in a stored procedure like this:

alter procedure test

with execute as owner as


EXEC sp_who2

I just see information about myself

View 5 Replies View Related

Creating Stored Procedure To Send Email To Multiple Users

Sep 20, 2007

Hi Everybody,

I am trying to setup a stored procedure that runs through a Reminders table and sends an email to users based on DateSent field being smaller than todays date. I have already setup the stored procedure to send the email, just having trouble looping through the recordset.

Code Snippet

CREATE PROCEDURE [dbo].[hrDB_SendEmail]



DECLARE @FirstName nvarchar(256),

@LastName nvarchar(256),

@To nvarchar(256),

@ToMgr nvarchar(256),

@Subject nvarchar(256),

@Msg nvarchar(256),

@DateToSend datetime,

@Sent nvarchar(256),

@ReminderID int,

@RowCount int,

@Today datetime,

@Result nvarchar(256)

-- Get the reminders to send


@ReminderID = r.intReminderID,

@DateToSend = r.datDateToSend,

@FirstName = e.txtFirstName,

@LastName = e.txtLastName,

@To = e.txtEmail,

@Subject = t.txtReminderSubject,

@Sent = r.txtSent


(auto_reminders r INNER JOIN employee e ON r.intEmployeeID = e.intEmployeeID) INNER JOIN ref_reminders t ON r.intReminderType = t.intReminderTempID


(((r.datDateToSend)<20/12/09) AND


-- Send the Emails

WHILE(LEN(@To) > 0)


EXEC @Result = sp_send_cdosysmail @To, @ToMgr, @Subject, @Msg


-- Mark the records as sent

IF @Result = 'sp_OAGetErrorInfo'


SELECT @Sent = 'Error'



SELECT @Sent = 'True'

UPDATE auto_reminders


auto_reminders.txtSent = @Sent, auto_reminders.datDateSent = @Today


intReminderID = @ReminderID



From the code you can probably tell I am new to writing stored procedures, so I apologise for any obvious errors. My major problems are :-

how to loop through each record

how to get todays date

whether the struture of the procedure is correct
Also, if you think there is an easier way or a better method, please suggest it. I am open to any suggestions you may have,

Thanks in advance

View 1 Replies View Related

Total SQL Users?

Jul 20, 2005

I am writing a paper for a computer programming college class and Ineed to know how many companies worldwide use SQL server? How manyservers does this constitute? At what rate is SQL use growing? If youcan't provide close to exact numbers, could you point me to a sourcewhere I could find them?

View 1 Replies View Related

Using Count(*) In A Stored Procedure

Jul 6, 2007

I would like to add custom paging to my ASP.Net pages. How can I use Count(*) in a query such as below to retrieve a record count? 
ALTER PROCEDURE [dbo].[view_icon_photos]    @Filenumber int = '0' , @Location nvarchar(50)= '-1' , @Rubric nvarchar(MAX)= '-1' , @Author nvarchar(75)= '-1' , @startRowIndex int= '-1' , @maximumRows int= '0'
IF @Filenumber = '0' AND @location > '-1' AND @Rubric = '-1' AND @Author = '-1' AND @startRowIndex > '-1' AND @maximumRows >'0'Select Icon, Filenumber, RowRankFrom(Select Icon, Filenumber,  Row_Number () Over ( Order By Filenumber ASC ) AS RowRankFrom dbo.photosWhere Location = @Location)As IconRank Where RowRank > @startRowIndex AND RowRank <= (@startRowIndex + @maximumRows)

View 2 Replies View Related

How Can I Use COUNT In My Stored Procedure?

Jul 29, 2007

i have a list of Categories and each one contains a list of SubCategories, and i use a nested Repeater to show each Category with their SubCategories, but because are to many to show verticaly, i want to make 2 nested repeaters and in the first one to show only the first "n" Categories with their SubCategories and in the second Repeater should be the last n Categories, and like so they will be in 2 colums
How can i use the COUNT function in my stored procedure to take only first n Categories?
I used SELECT * FROM Categories WHERE CategoryID <= 5 but i don't want to order by the primary key i want to order by a COUNT or something like this...
here is my stored procedure (i use it for two nested Repeaters)ALTER PROCEDURE SubCategoriiInCategorii
CategoryID int)
SELECT CategoryID, Name, Description FROM Categories WHERE CategoryID = @CategoryIDORDER BY Name
SELECT p.SubCategoryID, p.Name,p.CategoryID FROM SubCategorii p
i hope you understand what i mean, thank you

View 4 Replies View Related

Using Two COUNT(*) In A Stored Procedure

Apr 19, 2005

what's wrong with the following code? COUNT for completed and exempted doesn't return correct values. they return same values. but when i remove one count it's returning right COUNT. i need to return the COUNT from two tables with a single query. how can i accomplish that??? is there anything wrong with my code below?
CREATE PROCEDURE dbo.Test AsSELECT s.StudentIdNum,  c.[Name], COUNT(*) AS Completed, COUNT(*) AS exempted FROM StudentEnrolled AS s JOIN StudentCourse AS sc ON s.StudentKey = sc.StudentKey JOIN Courses AS c ON sc.CourseID = c.CourseIDLEFT JOIN ModuleEnrolment AS m ON sc.StudentCourseID = m.StudentCourseIDLEFT JOIN ModuleExemption AS e ON sc.StudentCourseID = e.StudentCourseIDWHERE m.Status = "Completed"GROUP BY s.StudentIdNum, c.[Name]

View 5 Replies View Related

SQL 2012 :: Allow Low Privilege User To Execute Stored Procedure To Create DB Users

Jul 22, 2014

I have a requirement to allow a user to restore a database and then create database users and add them to the db_owner database role. The user must not have sysadmin rights on the server.

The database restore works ok by placing the user in the dbcreator role.

There is a stored procedure to create the database user and alter role membership, I want the user to execute the sp as a different, higher privilege account so as not to give the user underlying permission to create users in the database.

USE [master]

/****** Object: StoredProcedure [dbo].[sp_create_db_users] Script Date: 22/07/2014 13:54:46 ******/

[Code] ....

The user has execute permission on the stored procedure but keeps getting the error:

Msg 916, Level 14, State 1, Line 2

The server principal "Mydomainadmin1" is not able to access the database "Mydatabase" under the current security context.

Mydomainadmin1 has dbowner to Mydatabase and sysadmin rights for server. If the 'execute as' is changed to 'caller' and run by mydomainadmin1 it works so the issue is between the execute sp and the actual running of the procedure.

View 1 Replies View Related

Obtain Unit Percent With Unit Count Divided By Total Count In Query

Aug 21, 2007

The following query returns a value of 0 for the unit percent when I do a count/subquery count. Is there a way to get the percent count using a subquery? Another section of the query using the sum() works.

Here is a test code snippet:

--Test Count/Count subquery

declare @Date datetime

set @date = '8/15/2007'

-- count returns unit data
Count(substring(m.PTNumber,3,3)) as PTCnt,
-- count returns total for all units

(select Count(substring(m1.PTNumber,3,3))

from tblVGD1_Master m1

left join tblVGD1_ClassIII v1 on m1.SlotNum_ID = v1.SlotNum_ID

Where left(m1.PTNumber,2) = 'PT' and m1.Denom_ID <> 9

and v1.Act = 1 and m1.Active = 1 and v1.MnyPlyd <> 0

and not (v1.MnyPlyd = v1.MnyWon and v1.ActWin = 0)

and v1.[Date] between DateAdd(dd,-90,@Date) and @Date) as TotalCnt,
-- attempting to calculate the percent by PTCnt/TotalCnt returns 0
(Count(substring(m.PTNumber,3,3)) /

(select Count(substring(m1.PTNumber,3,3))

from tblVGD1_Master m1

left join tblVGD1_ClassIII v1 on m1.SlotNum_ID = v1.SlotNum_ID

Where left(m1.PTNumber,2) = 'PT' and m1.Denom_ID <> 9

and v1.Act = 1 and m1.Active = 1 and v1.MnyPlyd <> 0

and not (v1.MnyPlyd = v1.MnyWon and v1.ActWin = 0)

and v1.[Date] between DateAdd(dd,-90,@Date) and @Date)) as AUPct
-- main select

from tblVGD1_Master m

left join tblVGD1_ClassIII v on m.SlotNum_ID = v.SlotNum_ID

Where left(m.PTNumber,2) = 'PT' and m.Denom_ID <> 9

and v.Act = 1 and m.Active = 1 and v.MnyPlyd <> 0

and not (v.MnyPlyd = v.MnyWon and v.ActWin = 0)

and v.[Date] between DateAdd(dd,-90,@Date) and @Date

group by substring(m.PTNumber, 3,3)

order by AUPct Desc

Thanks. Dan

View 1 Replies View Related

Transact SQL :: Can Invoke Stored Procedure Stored Inside From User Defined Table Column?

Nov 5, 2015

Can I invoke stored procedure stored inside from a user defined table column?

View 5 Replies View Related

TSQL Stored Procedure - Get Count Where....

Feb 23, 2007

I have the following for sql server 2000...
  Select b.courseName, a.courseId, count(a.courseId) as [count],  avg(convert(INT, a.fldScore)) as [average], count(fldPass) as [passed], count(fldPass) as [failed] From tblTest a  inner join tblTest2 b on a.courseId = b.courseId Group by a.courseId, b.courseName
Problem is the [passed] and [failed]
As it is, it's counting all of them.
I need to adjust it so passed will only read where fldPass = 'yes'
and fldPass = 'no' for the passed and failed.

View 4 Replies View Related

Dynamic Sql For Count In Stored Procedure

Apr 29, 2008

Hi all,
I'm using sql 2005. Can some one please tell me how to write dynamic sql for count. What i want is that i want to count the number of employees existing for the given department names and get the counted values as output into my 2.0 project.  If any one know who to write this please send the code.. Please help me.. I want the below code to change to dynamic sql:
 Alter proc GetCountforemp
@DestName varchar(200)=null,
@total int output
SELECT @total = Count(distinct Employee.EmployeeID) FROM Employee
INNER JOIN Dest R on R.DestID=Employee.DestID
WHERE R.DestName in ('''+@DestName+''')

View 1 Replies View Related

Stored Procedure For Each ProductID Count

Aug 5, 2004

Would like to get a total count from Quantity Column for (Each individual ProductID # entered) from the ProductID Column. And insert (the New total Value count into the QtySold Column.

Does anyone have an idea how to write a stored Procedure for this?

The tables name is OrderItems which contains the following columns:

uid, OrderID, ProductID, Quantity, QtySold, ProductName, Price,

Many Thanks

View 5 Replies View Related

Sum Or Count Value Of Field In Stored Procedure

Apr 19, 2005

How can i create a stored procedure that count or sum value of field

f1      f2    
f3    f4    f5
 record     1      
1      2     
3     1
and get answer  like this   1=4  - 2=1 -  3=1


View 1 Replies View Related

Stored Procedure - Return Count

Jun 16, 2005

Having a little trouble with this sp... just need to return the count.....CREATE  PROCEDURE dbo.getTotalObjectives @courseId   VARCHAR(20) ASBEGIN DECLARE @errCode     INT
  SELECT count(*)  FROM   objstructure  WHERE  courseId  = @courseId
 SET @errCode = 0  RETURN @errCode Can only return one thing, @errCode, but can return others in the select statement....I did it before like.....SELECT @lessonLocation = lessonLocation  FROM   cmiDataModel  WHERE  studentId = @studentIdand got the lessonLocationAnd, in code behind, I know this may be off as well....sObjNum = command.Parameters[ "@courseId" ].Value.ToString();The @courseId should be the count????Thanks all,Zath

View 4 Replies View Related

Column Count From Stored Procedure

Jul 20, 2005

I am trying to determine the number of columns that are returned froma stored procedure using TSQL. I have a situation where users will becreating their own procedures of which I need to call and place thoseresults in a temp table. I will not be able to modify those usersprocedures. I figure if I have the number of columns I can dynamicallycreate a temp table with the same number of columns, at which point Ican then perform an INSERT INTO #TempTableCreatedDynamically EXEC@UserProcCalled. With that said, does anyone have any idea how todetermine the number of rows that an SP will return in TSQL?Thanks!

View 2 Replies View Related

Calling A Stored Procedure Which Uses A Return @count

Aug 21, 2007

Hi again, and so soon...Having just solved my previous issue, I am now trying to call this stored proc from my page.aspx.vb code. Firstly the stored proc looks like this:-----------  ALTER PROCEDURE dbo.CountTEstAS   SET NOCOUNT ON    DECLARE @sql nvarchar(100);    DECLARE @recCount int;      DECLARE @parms nvarchar(100); SET @sql = 'SELECT @recCount1 = COUNT(*)            FROM Pool 'SET @parms = '@recCount1 int OUTPUT'             exec sp_executesql @sql, @parms, @recCount1 = @recCount OUTPUTRETURN @recCount -------------When tested from the stored proc, the result is: @RETURN_VALUE = 4  My code that calls this stored proc is:         Dim connect As New SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True")        connect.Open()        Dim cmd As New SqlCommand("CountTEst", connect)        cmd.CommandType = CommandType.StoredProcedure        Dim MyCount As Int32        MyCount = cmd.ExecuteScalar        connect.Close() So I expext MyCount = 4 but this code returns MyCount = 0 With the RETURN statement in the stored proc, and  then calling it via MyCount = cmd.ExecuteScalar, I didn't think I need to explicitly define any other parameters. Any help please. thanks, 

View 5 Replies View Related

SQL Problem Involving Count(*) In Stored Procedure

Jun 4, 2008

I seem to have a little problem with my SQL.  I'm attempting to use a an .NET grid-view to page a list of search results using an ObjectDataSource (ODS).  It's a very simple search setup.  The ODS retrieves the Search keyword from the query-string sending it to the BLL's GetResult method which then utilises the DAL's version and retrieves the result.  Not all of them of course because I'm paging so it only retrieves the first page (Lets say the first 10 items).  This part of the SQL works fine as the same SQL method is used else where on the site and it's well tested.  But to to use the Paging function I'm using the SelectCountMethod attribute of the ODS.  Again this gets the Search term from the QueryString and sends it too the BLL which retrieves the information from the DAL.  Now this is where it starts playing up.  The Sql count method is as follows and is run as a Stored Procedure: 1 ALTER PROCEDURE dbo.StoreName_Store_GetProductSearchCount
2 (
3 @SearchQuery nvarchar
4 )
5 AS
9 FROM StoreName_Products
10 WHERE Title LIKE '%' + @SearchQuery + '%'
Nice and Easy.  Not a Problem... Isn't it? When I run this query by selecting the database in the Server Explorer in VS2005  and running a 'New Query', it retrieves the correct results.  (I only run this query from the Start of the SELECT Query in this mode, don't add the stuff above it)When I run this query through the website as intended and retrieves the int from the Stored Procedure, it always returns the entire count of the number of products in the table.At first I thought It might be a simple error with my caching system.  Nope, it's not as after I purged it, it still returns the same value. I thought, well maybe just maybe the BLL or the DAL are some point converting it to this number but I'm quite sure it wasn't... and nope it wasn't that either because the ExecuteScalar method was found to be returning this number.  So I ran the Stored Procedure by opening it up and simply right clicking the SQL Query and Executing it adding a value for @SearchQuery when it requested.  Bingo.  It's returning the full number of the products.So my question is... What's the deal?  How can the same query return two completely different results?  and most of all... How do I overcome this?  Is this because it's in a stored procedure and I should be executing it as a SqlCommand from my DAL?  I'm a bit confused.  Is there a problem running this sort of query in a stored procedure that I don't know about and probably really should?Thankful for any answers,Regards,Luke 

View 11 Replies View Related

Count Records When RecordSource Is A Stored Procedure

Jul 20, 2005

I have a stored procedure named mySP that looks basically like this:Select Field1, Field2From tblMyTableWhere Field 3 = 'xyz'What I do is to populate an Access form:DoCmd.Openform "frmMyFormName"Forms!myFormName.RecordSource = "mySP"What I want to do in VBA is to open frmContinuous(a datasheet form) ifmySP returns more than one record or open frmDetail if mySP returnsonly one record.I'm stumped as to how to accomplish this, without running mySP twice:once to count it and once to use it as a recordsource.Thanks,lq

View 1 Replies View Related

Retrieve Count From Stored Procedure And Display In Datagrid.

Feb 9, 2006

Hi Guys,
I have a sql procedure that returns the following result when I execute it in query builder:
CountE   ProjStatus
6            In Progress
3            Complete
4            On Hold
The stored procedure is as follow:
SELECT     COUNT(*) AS countE, ProjStatusFROM         PROJ_ProjectsGROUP BY ProjStatus
This is the result I want but when I try to output the result on my page I get the following error:
DataBinder.Eval: 'System.Data.DataRowView' does not contain a property with the name Count.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Web.HttpException: DataBinder.Eval: 'System.Data.DataRowView' does not contain a property with the name Count.Source Error:

Line 271: </asp:TemplateColumn>
Line 272: <asp:TemplateColumn>
Line 273: <itemtemplate> <%# DataBinder.Eval(Container.DataItem, "Count" )%> </itemtemplate>
Line 274: </asp:TemplateColumn>
Line 275: </columns>
My page is as follows:
<script runat="server">
Dim myCommandPS As New SqlCommand("PROJ_GetProjStatus")

' Mark the Command as a SPROC
myCommandPS.CommandType = CommandType.StoredProcedure
Dim num as integer
num = CInt(myCommand.ExecuteScalar)
'Set the datagrid's datasource to the DataSet and databind
Dim myAdapterPS As New SqlDataAdapter(myCommandPS)
Dim dsPS As New DataSet()

dgProjSumm.DataSource = dsPS

<asp:datagrid id="dgProjSumm" runat="server"

Font-Names="Verdana,Arial,Helvetica; font-size: xx-small"

<asp:TemplateColumn HeaderText="Project Summary" HeaderStyle-Font-Bold="true" >
<itemtemplate> <%# BgColor(DataBinder.Eval(Container.DataItem, "ProjStatus" ))%> </itemtemplate>
<itemtemplate> <%# DataBinder.Eval(Container.DataItem, "Count" )%> </itemtemplate>
Please help if you can Im havin real trouble here.

View 3 Replies View Related

Copyrights 2005-15, All rights reserved