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.

Suggestions?

Thanks,

Zath

View 4 Replies


ADVERTISEMENT

Help With TSQL Stored Procedure - Error-Exec Point-Procedure Code

Nov 6, 2007

I am building a stored procedure that changes based on the data that is available to the query. See below.
The query fails on line 24, I have the line highlighted like this.
Can anyone point out any problems with the sql?

------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------
This is the error...


Msg 8114, Level 16, State 5, Procedure sp_SearchCandidatesAdvanced, Line 24

Error converting data type varchar to numeric.

------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------
This is the exec point...


EXEC [dbo].[sp_SearchCandidatesAdvanced]

@LicenseType = 4,

@PositionType = 4,

@BeginAvailableDate = '10/10/2006',

@EndAvailableDate = '10/31/2007',

@EmployerLatitude = 29.346675,

@EmployerLongitude = -89.42251,

@Radius = 50

GO

------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------
This is the STORED PROCEDURE...


set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

go



ALTER PROCEDURE [dbo].[sp_SearchCandidatesAdvanced]

@LicenseType int = 0,

@PositionType int = 0,

@BeginAvailableDate DATETIME = NULL,

@EndAvailableDate DATETIME = NULL,

@EmployerLatitude DECIMAL(10, 6),

@EmployerLongitude DECIMAL(10, 6),

@Radius INT


AS


SET NOCOUNT ON


DECLARE @v_SQL NVARCHAR(2000)

DECLARE @v_RadiusMath NVARCHAR(1000)

DECLARE @earthRadius DECIMAL(10, 6)


SET @earthRadius = 3963.191


-- SET @EmployerLatitude = 29.346675

-- SET @EmployerLongitude = -89.42251

-- SET @radius = 50


SET @v_RadiusMath = 'ACOS((SIN(PI() * ' + @EmployerLatitude + ' / 180 ) * SIN(PI() * p.CurrentLatitude / 180)) + (COS(PI() * ' + @EmployerLatitude + ' / 180) * COS(PI() * p.CurrentLatitude / 180) * COS(PI()* p.CurrentLongitude / 180 - PI() * ' + @EmployerLongitude + ' / 180))) * ' + @earthRadius




SELECT @v_SQL = 'SELECT p.*, p.CurrentLatitude, p.CurrentLongitude, ' +

'Round(' + @v_RadiusMath + ', 0) AS Distance ' +

'FROM ProfileTable_1 p INNER JOIN CandidateSchedule c on p.UserId = c.UserId ' +

'WHERE ' + @v_RadiusMath + ' <= ' + @Radius


IF @LicenseType <> 0

BEGIN

SELECT @v_SQL = @v_SQL + ' AND LicenseTypeId = ' + @LicenseType

END


IF @PositionType <> 0

BEGIN

SELECT @v_SQL = @v_SQL + ' AND Position = ' + @PositionType

END


IF LEN(@BeginAvailableDate) > 0

BEGIN

SELECT @v_SQL = @v_SQL + ' AND Date BETWEEN ' + @BeginAvailableDate + ' AND ' + @EndAvailableDate

END


--SELECT @v_SQL = @v_SQL + 'ORDER BY CandidateSubscriptionEmployerId DESC, CandidateFavoritesEmployerId DESC, Distance'


PRINT(@v_SQL)

EXEC(@v_SQL)


-----------------------------------------------------------------------------------------------------------------

View 4 Replies View Related

TSQL - Stored Procedure

Jun 11, 2001

I have an insert stored procedure which creates a customer. The customer has a ID which is an autonumber within the SQL server table.

I want to output this value to use this to update another table. How do I output a value of an insert query which i am not passing in as it's an autonumber ??

I am sure someone has come accross this before. Is it a trigger solution ?? Any ideas very welcome.

mark

View 2 Replies View Related

How To Execute A Url In Tsql Stored Procedure

Feb 29, 2008

Can i execute a URL in tsql stored procedure.
Waht i want's is to hit a url on some event.
I know i can do it in CLR stored procedure but for that i have to deploy assembly on the server which i want's to avoid.
Is there any way i can hit a url from tsql stored procedure

Kamran Shahid
Sr. Software Engineer(MCSD.Net)
www.netprosys.com

View 8 Replies View Related

Walking Up The Tree In Tsql Or Stored Procedure

Apr 3, 2008

Well I have a two tables lets say they look like as follows:

Table A
CompanyID
Location

TableB
CompanyID
CompanyName
Date


The CompanyID column has values that look like this:

AAA OR
AAA.BBB OR
AAA.BBB.CCC OR
AAA.BBB.CCC.DDD OR
AAA.BBB.CCC.DDD.EEE OR
AAA.BBB.CCC.DDD.EEE.FFF

each line representing the level of the company.


we can see that CompanyID column exists in both tables. and I would like to find out the CompanyName from table B for each companyID that exists in Table A.


but the tricky part is that for a specific CompanyID in tableA I might not have a exact match.
e.g. in A lets say I have AAA.BBB.CCC.DDD.EEE for CompanyID but in table B i might not have AAA.BBB.CCC.DDD.EEE but instead have AAA.BBB or AAA.BBB.CCC or AAA.

so I have to walk up the tree or these levels to look for a match an get the companyName. the match logic is as such.

If in table A companyID = AAA.BBB.CCC.DDD.EEE then look for same value in B if NOT FOUND then
remove the last level from the companyID value from Table A. so new value of CompanyID = AAA.BBB.CCC.DDD
Now look for this new value AAA.BBB.CCC.DDD in table B. IF NOT FOUND then

remove another level from ComapnyID in table A so new companyID = AAA.BBB.CCC and look for
AAA.BBB.CCC in table B. just going up the tree by chopping off a level till I find a match.

now the question is how to do this in TSQL.... can someone help?

So what I really want to do is to look for a match between A and B based on companyID.

View 2 Replies View Related

Execution Time Gap Between Simple Tsql And Stored Procedure In SQl Server 2005

Oct 16, 2007

Hi ,

I ma using sql server 2005.I have a bunch of statements of sql and i have created a stored procedure for those. When i execute i found that there is lot's of difference between execution time of stored procedure and direct sql in query windows.

can anyone help me to optimize the execution time for stored prcedure even stored prcedure is very simple.
I have used sql server 2000 and i am new in sql server 2005.

View 1 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
Thanks

View 10 Replies View Related

Using Count(*) In A Stored Procedure

Jul 6, 2007

Hi,
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? 
set ANSI_NULLS ONset QUOTED_IDENTIFIER ONGO
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'
As
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

hello,
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)
AS
SELECT CategoryID, Name, Description FROM Categories WHERE CategoryID = @CategoryIDORDER BY Name
 
SELECT p.SubCategoryID, p.Name,p.CategoryID FROM SubCategorii p
ORDER BY p.Name
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?
<code>
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]
</code>

View 5 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 vb.net 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
as
begin
SELECT @total = Count(distinct Employee.EmployeeID) FROM Employee
INNER JOIN Dest R on R.DestID=Employee.DestID
WHERE R.DestName in ('''+@DestName+''')
end 

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
e.g.

               
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
6 SET NOCOUNT ON
7
8 SELECT COUNT(*)
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

Running Total Count In Stored Procedure

Jul 20, 2005

in my procedure, I want to count the number of rows that have erroredduring an insert statement - each row is evaluated using a cursor, soI am processing one row at a time for the insert. My total count tobe displayed is inside the cursor, but after the last fetch is called.Wouldn't this display the last count? The problem is that the count isalways 1. Can anyone help?here is my code,.... cursor fetchbegin ... cursorif error then:beginINSERT INTO US_ACCT_ERRORS(ERROR_NUMBER, ERROR_DESC, cUSTOMERNUMBER,CUSTOMERNAME, ADDRESS1, ADDRESS2, CITY,STATE, POSTALCODE, CONTACT, PHONE, SALESREPCODE,PRICELEVEL, TERMSCODE, DISCPERCENT, TAXCODE,USERCOMMENT, CURRENCY, EMAILADDRESS, CUSTOMERGROUP,CUSTINDICATOR, DT_LOADED)VALUES(@ERRORNUM, @ERRORDESC,@CUSTOMERNUMBER, @CUSTOMERNAME, @ADDRESS1, @ADDRESS2, @CITY,@STATE, @POSTALCODE, @CONTACT, @PHONE, @SALESREPCODE,@PRICELEVEL, @TERMSCODE, @DISCPERCENT, @TAXCODE,@USERCOMMENT, @CURRENCY, @EMAILADDRESS, @CUSTOMERGROUP,@CUSTINDICATOR, @DTLOADED)SET @ERRORCNT = @ERRORCNT + 1END --error--FETCH NEXT FROM CERNO_US INTO@CUSTOMERNUMBER, @CUSTOMERNAME, @ADDRESS1, @ADDRESS2, @CITY, @STATE,@POSTALCODE, @CONTACT,@PHONE,@SALESREPCODE, @PRICELEVEL,@TERMSCODE,@DISCPERCENT, @TAXCODE, @USERCOMMENT, @CURRENCY,@EMAILADDRESS,@CUSTOMERGROUP, @CUSTINDICATOR, @DTLOADED--IF @ERRORCNT > 0INSERT INTO PROCEDURE_RESULTS(PROCEDURE_NAME, TABLE_NAME, ROW_COUNT,STATUS)VALUES('LOAD_ACCOUNTS', 'LOAD_ERNO_US_ACCT', @ERRORCNT, 'FAILEDINSERT/UPDATE')END -- cursorCLOSE CERNO_USDEALLOCATE CERNO_US

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 asp.net 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 asp.net 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()
myAdapter.Fill(dsPS)

dgProjSumm.DataSource = dsPS
dgProjSumm.DataBind()

myConnection.Close()
</script>
 
<asp:datagrid id="dgProjSumm" runat="server"

BorderWidth="0"
Cellpadding="4"
Cellspacing="0"
Width="100%"
Font-Names="Verdana,Arial,Helvetica; font-size: xx-small"
Font-Size="xx-small"
AutoGenerateColumns="false">

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

View 3 Replies View Related

Row Count For Any Stored Procedure - OPENQUERY No Longer Works

Mar 12, 2015

I have a process that keeps check on the row counts of about 100 stored procedures. The input parameters and "certified" row counts for all of the stored procedures are stored in a database. The process runs every day and executes all of the stored procedures using the parameters from the database with syntax below. The row count returned is compared against the known "certified" row count. If the counts are different, we receive an email alerting us that something has changed with the data or the sp query.

(This code is dynamically generated for all 100 + stored procedures)

SELECT COUNT(*) FROM OPENQUERY(SQLSERVER,'EXEC 'usp_HR_My_Stored_Procedure @inputparam1="12345",@inputparam2="12345"')

This worked well until I upgraded from SQL Server 2008 R2 to SQL Server 2014. Evidently Microsoft fixed this for me. The error below is now received anytime we attempt to execute a stored procedure with dynamic SQL through OPENQUERY.

The metadata could not be determined because statement 'EXEC (@sql_str)' in procedure 'usp_HR_My_Stored_Procedure ' contains dynamic SQL. Consider using the WITH RESULT SETS clause to explicitly describe the result set.

The stored procedures that are monitored change frequently, so it isn't reasonable to create tables with fixed column structures for all for all of the stored procs.

View 5 Replies View Related

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
(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 View Related

Stored Procedure To Count Matching Words Between Two Strings

Jan 19, 2007

hi all,

I want to know that how can i write a stored procedure that takes an input param, i.e., a string and returns the count of the matching words between the input parameter and the value of a column in a table. e.g. I have a table Person with a column address. now my stored procedure matches and counts the number of words that are common between the address of the person and the input param string. I am looking forward for any help in this matter. I am using Sql server 2005.

View 1 Replies View Related

SQL Server 2012 :: Can't Get Row Count To Return To Calling Stored Procedure

Jul 9, 2014

SQL Server 2012 Standard SP 1.

Stored procedure A calls another stored procedure B. Rowcount is set properly in called procedure B, but does not seem to return it to calling procedure A. Otherwise the two stored procedures are working correctly. Here is the relevant code from the calling procedure A:

declare @NumBufferManagerRows int = 0;
exec persist.LoadBufferManager @StartTicks, @EndTicks, @TimeDiff, @NumBufferManagerRows;
print 'BufferManagerRows';
print @NumBufferManagerRows;

Print statement prints @NumBufferManagerRows as 0.

Here is the called stored procedure B:

CREATE PROCEDURE [persist].[LoadBufferManager]
-- Add the parameters for the stored procedure here
@StartTicks bigint,
@EndTicks bigint,
@TimeDiff decimal(9,2),
@NumRows int OUTPUT

[Code] ...

View 2 Replies View Related

Integration Services :: Log Inserted And Updated Count Done By Stored Procedure

Sep 8, 2015

I am run a stored procedure using Execute SQL task in, I want to log information of number of record inserted update in my table. I want to enable SSIS logging after from where I get information number of record inserted update.

I am using SQL server 2008R2 standard edition.

View 4 Replies View Related

TSQL: I Want To Use A SELECT Statement With COUNT(*) AS 'name' And ORDER BY 'name'

Jul 23, 2005

I am very new to Transact-SQL programming and don't have a programmingbackground and was hoping that someone could point me in the rightdirection. I have a SELECT statement SELECT FIXID, COUNT(*) AS IOIsand want to ORDER BY 'IOI's'. I have been combing through the BOL, butI don't even know what topic/heading this would fall under.USE INDIISELECT FIXID, COUNT(*) AS IOIsFROM[dbo].[IOI_2005_03_03]GROUP BY FIXIDORDER BY FIXIDI know that it is a simple question, but perhaps someone could assistme.Thanks,

View 18 Replies View Related

TSQL - Count The Number Of Records In A Table

Sep 24, 2007

Hi guys,
Is there any function to get the total number of records in a specific table?
(SQL SERVER 2000).
Thanks in advance,
Aldo.

View 3 Replies View Related

TSQL Strored Procedure

Apr 26, 2006

I am having an issue when trying to pull data from Oracle into a sqlSERVER TABLE. I'm running into an issue because I am using to much temporary space in Oracle because the return set is so large. New to sqlserver, but in Oracle the solution would be to commmit the insert after so many records have been retrieved.



Here's the procedure I wrote I would think I need to add a cursor and a counter which be used to do a commit after so many rows have been retrieved. DOes so one have a procedure I could model mine after?



ALTER PROCEDURE [dbo].[SP_Load_BO]

-- Add the parameters for the stored procedure here

@p1 int = 0,

@p2 int = 0

AS

BEGIN



SET NOCOUNT ON;

INSERT INTO MERCHANT_BACKOFFICE_SQLSERVER

(MONTHYEAR,ALLIANCEID, merchantid,rptservid,scid,tabletype,tablenum,VOLUME, COST, COSTPLUS,DATELOAD)

SELECT convert(DATETIME,PERIOD) as PERIOD,

ALLIANCEID,

merchantid,

rpTSERVID,

scid,

tabletype,

tablenum,

Convert(numeric(10),Count) AS VOLUME,

Convert(numeric(24,6),COST) as COST,

Convert(numeric(24,6),COSTPLUS) as COSTPLUS,

convert(datetime,DATE_LOAD) as DATE_LOAD

from

OPENQUERY(INV,'

SELECT MER.MONTHYEAR AS PERIOD,

MER.ALLIANCEID,

MER.merchantid,

MER.RPTSERVID,

MER.SCID,

MER.TABLETYPE,

MER.TABLENUM,

SUM(MER.VOLUME) AS Count,

SUM(MER.COST) as Cost,

SUM(MER.COSTPLUS) as Costplus,

to_char((last_day(add_months(sysdate,-1))+1),''MM/DD/YYYY'') as DATE_LOAD

FROM

MERCHANT_BACKOFFICE_SERVICE MER

WHERE MER.allianceid <>516

group by MER.MONTHYEAR,

MER.ALLIANCEID,

MER.merchantid,

MER.RPTSERVID,

MER.SCID,

MER.TABLETYPE,

MER.TABLENUM')

END

View 5 Replies View Related

Calling A Stored Procedure Inside Another Stored Procedure (or Nested Stored Procedures)

Nov 1, 2007

Hi all - I'm trying to optimized my stored procedures to be a bit easier to maintain, and am sure this is possible, not am very unclear on the syntax to doing this correctly.  For example, I have a simple stored procedure that takes a string as a parameter, and returns its resolved index that corresponds to a record in my database. ie
exec dbo.DeriveStatusID 'Created'
returns an int value as 1
(performed by "SELECT statusID FROM statusList WHERE statusName= 'Created') 
but I also have a second stored procedure that needs to make reference to this procedure first, in order to resolve an id - ie:
exec dbo.AddProduct_Insert 'widget1'
which currently performs:SET @statusID = (SELECT statusID FROM statusList WHERE statusName='Created')INSERT INTO Products (productname, statusID) VALUES (''widget1', @statusID)
I want to simply the insert to perform (in one sproc):
SET @statusID = EXEC deriveStatusID ('Created')INSERT INTO Products (productname, statusID) VALUES (''widget1', @statusID)
This works fine if I call this stored procedure in code first, then pass it to the second stored procedure, but NOT if it is reference in the second stored procedure directly (I end up with an empty value for @statusID in this example).
My actual "Insert" stored procedures are far more complicated, but I am working towards lightening the business logic in my application ( it shouldn't have to pre-vet the data prior to executing a valid insert). 
Hopefully this makes some sense - it doesn't seem right to me that this is impossible, and am fairly sure I'm just missing some simple syntax - can anyone assist?
 

View 1 Replies View Related

TSQL Or Procedure To Compute According To Previous Data

May 19, 2008

I have three coloumn in Salary Table
Emp ID, Emp Salary , Sequence
a1 1000 1
a1 2000 2
a1 2000 3
a2 4000 1
a2 5000 2
a2 5000 3
a2 6000 4



Now I have to calculate the count on salary if the previous salary is different then count +1 else is previous salary same then add +0.
so output be
EmpID and Updation in Salary
a1 = 2 and for a2 =3

Can anyone help me with the query or storeprocedure i can achieve this output counting according to previous data.

View 9 Replies View Related

Debugging TSQL Stored Procedures

Jun 23, 2006

Running SQL Server Express is there a way to debug TSQL stored procedures? I also have Visual Studio .NET 2003, can I use it to debug the TSQL stored procedures?

Thanks in advance,
Mark

View 7 Replies View Related

Best Way To Compile Thousands Of TSQL Stored Procedures?

Jul 23, 2005

I have a custom application that on occasion requires thousands of TSQLfiles (on the file system) to be compiled to the database.What is the quickest way to accomplish this?We currently have a small vbs script that gets a list of all the files,the loops around a call to "osql". each call to osql opens/closes aconnection to the destination database (currently across the network).

View 5 Replies View Related

Calling A Stored Procedure From ADO.NET 2.0-VB 2005 Express: Working With SELECT Statements In The Stored Procedure-4 Errors?

Mar 3, 2008

Hi all,

I have 2 sets of sql code in my SQL Server Management Stidio Express (SSMSE):

(1) /////--spTopSixAnalytes.sql--///

USE ssmsExpressDB

GO

CREATE Procedure [dbo].[spTopSixAnalytes]

AS

SET ROWCOUNT 6

SELECT Labtests.Result AS TopSixAnalytes, LabTests.Unit, LabTests.AnalyteName

FROM LabTests

ORDER BY LabTests.Result DESC

GO


(2) /////--spTopSixAnalytesEXEC.sql--//////////////


USE ssmsExpressDB

GO
EXEC spTopSixAnalytes
GO

I executed them and got the following results in SSMSE:
TopSixAnalytes Unit AnalyteName
1 222.10 ug/Kg Acetone
2 220.30 ug/Kg Acetone
3 211.90 ug/Kg Acetone
4 140.30 ug/L Acetone
5 120.70 ug/L Acetone
6 90.70 ug/L Acetone
/////////////////////////////////////////////////////////////////////////////////////////////
Now, I try to use this Stored Procedure in my ADO.NET-VB 2005 Express programming:
//////////////////--spTopSixAnalytes.vb--///////////

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim sqlConnection As SqlConnection = New SqlConnection("Data Source = .SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = ssmsExpressDB;")

Dim sqlDataAdapter As SqlDataAdapter = New SqlDataAdaptor("[spTopSixAnalytes]", sqlConnection)

sqlDataAdapter.SelectCommand.Command.Type = CommandType.StoredProcedure

'Pass the name of the DataSet through the overloaded contructor

'of the DataSet class.

Dim dataSet As DataSet ("ssmsExpressDB")

sqlConnection.Open()

sqlDataAdapter.Fill(DataSet)

sqlConnection.Close()

End Sub

End Class
///////////////////////////////////////////////////////////////////////////////////////////

I executed the above code and I got the following 4 errors:
Error #1: Type 'SqlConnection' is not defined (in Form1.vb)
Error #2: Type 'SqlDataAdapter' is not defined (in Form1.vb)
Error #3: Array bounds cannot appear in type specifiers (in Form1.vb)
Error #4: 'DataSet' is not a type and cannot be used as an expression (in Form1)

Please help and advise.

Thanks in advance,
Scott Chang

More Information for you to know:
I have the "ssmsExpressDB" database in the Database Expolorer of VB 2005 Express. But I do not know how to get the SqlConnection and the SqlDataAdapter into the Form1. I do not know how to get the Fill Method implemented properly.
I try to learn "Working with SELECT Statement in a Stored Procedure" for printing the 6 rows that are selected - they are not parameterized.




View 11 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved