Custom Paging On Stored Procedure

Oct 12, 2007

Hello,
       I receive this error "Incorrect syntax near 'GetGalleryPaged'." I'm trying to use custom paging on a stored procedure.
 
.......
       Dim mySqlConn As New SqlConnection(ConnStr)
        Dim objDA As New SqlDataAdapter("GetGalleryPaged", mySqlConn)
        objDA.SelectCommand.Parameters.Add("@startRowIndex", SqlDbType.Int, 1)
        objDA.SelectCommand.Parameters.Add("@@maximumRows", SqlDbType.Int, 9)
        Dim objDS As New DataSet()
        Dim objPds As PagedDataSource = New PagedDataSource
        objDA.Fill(objDS, "Gallery") <<----error here
        mySqlConn.Close()

        objPds.DataSource = objDS.Tables(0).DefaultView
        objPds.AllowPaging = True

.......
 ALTER PROCEDURE dbo.GetGalleryPaged
(
     @startRowIndex int,
     @maximumRows int
)
AS
    SELECT     idgallery, g_picpath
    FROM         
    (        SELECT idgallery, g_picpath, ROW_NUMBER() OVER (ORDER BY idgallery DESC) AS RowRank
            FROM Gallery
    ) AS GalleryWithRowNumber
    WHERE     RowRank > @startRowIndex AND RowRank <= (@startRowIndex + @maximumRows)
    ORDER BY idgallery DESC
 
 
cheers,
imperialx 

View 5 Replies


ADVERTISEMENT

I Am Using A Stored Procedure For Paging....

Aug 29, 2007

However it is not saving in visual srudio 2005. it is saying 'ambiguous column name ID' does anyone know why?CREATE PROCEDURE PagedResults_New
(@startRowIndex int,
@maximumRows int
)
AS
 
--Create a table variable
DECLARE @TempItems TABLE
(ID int IDENTITY,
ShortListId int
)
-- Insert the rows from tblItems into the temp. table
INSERT INTO @TempItems (ShortListId)
SELECT Id
FROM Shortlist SWHERE Publish = 'True' order by date DESC
 
-- Now, return the set of paged records
SELECT S.*FROM @TempItems t
INNER JOIN ShortList S ON
t.ShortListId = S.Id
 
WHERE ID BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1

View 3 Replies View Related

Paging Through Stored Procedure

Nov 14, 2005

I have a stored procedure which returns the results fine, i.e. my asp code of

do while not objRS.EOF
display record n
objRS.Movenext
Loop

Included in the stored procedure is the number of pages that are ultimately returned, however I don't know how to access that value from my asp code.

Here is the stored procedure. I want to get the value of PageCount from my ASP code????

CREATE PROCEDURE GetSortedPage(
@TableName VARCHAR(50),
@PrimaryKey VARCHAR(25),
@SortField VARCHAR(100),
@PageSize INT,
@PageIndex INT = 1,
@QueryFilter VARCHAR(100) = NULL
) AS
SET NOCOUNT ON

DECLARE @SizeString AS VARCHAR(5)
DECLARE @PrevString AS VARCHAR(5)

SET @SizeString = CONVERT(VARCHAR, @PageSize)
SET @PrevString = CONVERT(VARCHAR, @PageSize * (@PageIndex - 1))

IF @QueryFilter IS NULL OR @QueryFilter = ''
BEGIN

EXEC(
'SELECT * FROM ' + @TableName + ' WHERE ' + @PrimaryKey + ' IN
(SELECT TOP ' + @SizeString + ' ' + @PrimaryKey + ' FROM ' + @TableName + ' WHERE ' + @PrimaryKey + ' NOT IN
(SELECT TOP ' + @PrevString + ' ' + @PrimaryKey + ' FROM ' + @TableName + ' ORDER BY ' + @SortField + ')
ORDER BY ' + @SortField + ')
ORDER BY ' + @SortField
)
EXEC('SELECT (COUNT(*) - 1)/' + @SizeString + ' + 1 AS PageCount FROM ' + @TableName)

END
ELSE
BEGIN

EXEC(
'SELECT * FROM ' + @TableName + ' WHERE ' + @PrimaryKey + ' IN
(SELECT TOP ' + @SizeString + ' ' + @PrimaryKey + ' FROM ' + @TableName + ' WHERE ' + @QueryFilter + ' AND ' + @PrimaryKey + ' NOT IN
(SELECT TOP ' + @PrevString + ' ' + @PrimaryKey + ' FROM ' + @TableName + ' WHERE ' + @QueryFilter + ' ORDER BY ' + @SortField + ')
ORDER BY ' + @SortField + ')
ORDER BY ' + @SortField
)
EXEC('SELECT (COUNT(*) - 1)/' + @SizeString + ' + 1 AS PageCount FROM ' + @TableName + ' WHERE ' + @QueryFilter)

END

RETURN 0
GO

View 5 Replies View Related

Paging Query Without Using Stored Procedure

Dec 1, 2006

Hello, my table is clustered according to the date. Has anyone found an efficient way to page through 16 million rows of data? The query that I have takes waaaay too long. It is really fast when I page through information at the beginning but when someone tries to access the 9,000th page sometimes it has a timeout error. I am using sql server 2005 let me know if you have any ideas. Thanks
 I am also thinking about switch datavase software to something that can handle that many rows. Let me know if you have a suggestion on a particular software that can handle paging through 16 million rows of data.

View 1 Replies View Related

I Want To Do Paging In A Stored Procedure, But Have Some Problem With It

Jan 15, 2004

my procedure is like this
////////////////////////////////////
CREATE PROCEDURE dbo.test2
(
@Page_No int,
@PageSize int,
@RowCount int output
)
AS

declare @intBeginID int
declare @intEndID int
declare @Counter int

set @Counter = 1
select @RowCount = count(*) from project

declare cro_fastread cursor scroll
for select * from project order by sector
open cro_fastread

select @intBeginID=(@Page_No-1)*@PageSize+1
select @intEndID = @intBeginID+@PageSize-1

fetch absolute @intBeginID from cro_fastread

WHILE @@FETCH_STATUS = 0 and @Counter < @PageSize
BEGIN
set @Counter = @Counter + 1
FETCH NEXT FROM cro_fastread
END

close cro_fastread
deallocate cro_fastread
/////////////////////////////////////////
my problem is the "FETCH" method can only get a row at one time, so there would be return many recordsets, how can I merge all the return recordset into one.
thanks in advance!

View 17 Replies View Related

Filtering+ordering+paging In One Stored Procedure

Feb 21, 2008

Hi Everybady
Currenctly I have facing a problem on how to create a stored procedure that able to filter the data and order it dynamically on selected row.
does anyone know how to do that
I have successfully create a stored procedure that able to order with any colume at any direction and select it from rownumber to another rownumber.
But i have failed to add another function with is where claus to do filtering on the data after ordering and selection
does anybody can give me a example about that?
Thanks a lot

View 9 Replies View Related

Sorting + Paging A Large Table In Stored Procedure

May 6, 2007

As I said above, how do I put sorting + paging in a stored procedure.My database has approximately 50000 records, and obviously I can't SELECT all of them and let GridView / DataView do the work, right? Or else it would use to much resources per one request.So I intend to use sorting + paging at the database level. It's going to be either hardcode SQL or stored procedures.If it's hardcode SQL, I can just change SQL statement each time the parameters (startRecord, maxRecords, sortColumns) change.But I don't know what to do in stored procedure to get the same result. I know how to implement paging in stored procedure (ROW_NUMBER) but I don't know how to change ORDER BY clause at runtime in the stored procedure.Thanks in advance.PS. In case "ask_Scotty", who replied in my previous post,   http://forums.asp.net/thread/1696818.aspx, is reading this, please look at my reply on your answer in the last post. Thank you.

View 3 Replies View Related

Evaluate My Stored Procedure For Paging, Filtering, And Sorting

Apr 28, 2008

This is for SQL Server 2000. The purpose of the procedure is to return a subset of a filtered and sorted result set. The subset, filter criteria, and sort column and sort direction can be set dynamically. It uses the rowcount technique for paging.

This would be used to drive an ASP.NET gridview which supports filtering of the data, paging, and sorting. Please let me know what improvements I can make or if you have an idea for a better solution. (I didn't put this in a vBulletin code block because personally I find two sets of scroll bars annoying, but I can if people think it's better).

CREATE PROCEDURE dbo.Books_GetFilteredSortedSubset
(
-- paging
@startRowIndex INT = 1,
@maximumRows INT = 999999,

-- sorting
@sortColumn NVARCHAR(30) = 'title_id',
@sortDirection NVARCHAR(4) = 'ASC',

-- filtering
@title VARCHAR(100) = NULL,
@type VARCHAR(30) = NULL,
@price MONEY = NULL
)
AS
BEGIN

DECLARE @sql NVARCHAR(4000)
DECLARE @parameters NVARCHAR(4000)
DECLARE @tableSource NVARCHAR(4000)
DECLARE @orderByExpression NVARCHAR(4000)
DECLARE @searchCondition NVARCHAR(4000)
DECLARE @uniqueKey NVARCHAR(30)


-- set the unique key used to ensure the rows are sorted deterministically
SET @uniqueKey = 'title_id'



-- build the FROM table source used throughout this procedure
SET @tableSource = 'titles t
inner join publishers p on t.pub_id = p.pub_id'




-- build the WHERE search condition used to control filtering throughout this procedure

SET @searchCondition = '(1 = 1)'

IF @title IS NOT NULL
SET @searchCondition = @searchCondition + ' AND (title LIKE ''%' + @title + '%'')'
IF @type IS NOT NULL
SET @searchCondition = @searchCondition + ' AND (type LIKE ''' + @type + '%'')'
IF @price IS NOT NULL
SET @searchCondition = @searchCondition + ' AND (price = ' + CAST(@price AS NVARCHAR) + ')'




-- build the ORDER BY expression used to control the sorting throughout this procedure

SET @orderByExpression = @sortColumn + ' ' + @sortDirection

-- add uniqeKey to ORDER BY statement to ensure consistent ordering of results when @sortColumn is not unique
IF @sortColumn <> @uniqueKey
SET @orderByExpression = @orderByExpression + ', ' + @uniqueKey + ' ' + @sortDirection





-- Get the column value at the position specified by @startRowIndex when the results are sorted in the desired sort order

SET @sql = 'SET ROWCOUNT @rowcount; SELECT @start_row = ' + @sortColumn + ', @start_row_id = ' + @uniqueKey +
' FROM ' + @tableSource +
' WHERE ' + @searchCondition + ' ORDER BY ' + @orderByExpression

PRINT @sql

SET @parameters = '@rowcount INT, @start_row sql_variant OUTPUT, @start_row_id sql_variant OUTPUT'

DECLARE @start_row sql_variant
DECLARE @start_row_id sql_variant

EXEC sp_executesql @sql, @parameters, @rowcount = @startRowIndex, @start_row = @start_row OUTPUT, @start_row_id = @start_row_id OUTPUT



-- Get the filtered subset of results

-- add sql to filter the results based on criteria passed in as parameters
SET @sql = 'SET ROWCOUNT @rowcount; ' +
'SELECT
t.title_id,
t.title,
t.price,
t.type,
p.pub_name,
p.city,
p.state,
p.country
FROM ' + @tableSource +
' WHERE (' + @searchCondition + ') AND '

-- add sql to control the starting row
IF @sortDirection = 'ASC'
SET @sql = @sql + '( (' + @sortColumn + ' > @start_row) OR (' +
@sortColumn + ' = @start_row AND ' + @uniqueKey + ' >= @start_row_id) )'
ELSE
SET @sql = @sql + '( (' + @sortColumn + ' < @start_row) OR (' +
@sortColumn + ' = @start_row AND ' + @uniqueKey + ' <= @start_row_id) )'

-- add sql to control the ordering of everything
SET @sql = @sql + ' ORDER BY ' + @orderByExpression

PRINT @sql

SET @parameters = '@rowcount INT, @start_row sql_variant, @start_row_id sql_variant'

EXEC sp_executesql @sql, @parameters, @rowcount = @maximumRows, @start_row = @start_row, @start_row_id = @start_row_id


-- Reset the rowcount for others
SET ROWCOUNT 0

END;
GO

View 14 Replies View Related

Custom Paging

May 23, 2005

Im in the process of trying to teach myself SqlServer, comming from Oracle.  How the heck do I get the equivlent of  %ROWNUM pseudo-column in SqlServer?  Top just isn't doing it for me.
 Oracle Example wrote:
Select * from foo where foo%ROWNUM > 10 and foo%ROWNUM <20;

View 12 Replies View Related

SP Works But I Need Help In Custom Paging

Jan 17, 2005

I need to be able to specify which column to sort by, BUT SQL 2000 does not allow me to

SELECT * FROM #TempTable
WHERE ID > @FirstRec
AND
ID < @LastRec
AND
EmployerID = @EmployerID
AND
Job_no = @Job_no

ORDER BY @WHICHCOLUMN asc

You can see that @WHICHCOLUMN is can be Surname, Age ETC, I have tried to make it a variable but, it started complaining of @FIRSTREC not defined, what's going on pls help, However, how do you combine dynamic queries with parameters as the say

"Sql server does not accept variables as part of sql"

my yahoo is abujajob@yahoo.com















WORKING CODE without WHICHCOLUMN

CREATE PROCEDURE [GetApplicants]
@CurrentPage int,
@PageSize int,
@TotalRecords int output,
@EmployerID int,
@Job_no int,
@WhichColumn varchar,
@SortBy varchar
AS
--Create a temp table to hold the current page of data
--Add and ID column to count the records
CREATE TABLE #TempTable
(
ID int IDENTITY PRIMARY KEY,
Job_no int,
EmployerID int,
JobseekersID int,
Email varchar (100)

)
--Fill the temp table with the Customers data
INSERT INTO #TempTable
(
Job_no, EmployerID,JobseekersID,Email

)

SELECT Job_no, EmployerID,JobseekersID,Email FROM ApplicantsManagement

--Create variable to identify the first and last record that should be selected

DECLARE @myStatement varchar(500)
DECLARE @FirstRec int, @LastRec int
SELECT @FirstRec = (@CurrentPage - 1) * @PageSize
SELECT @LastRec = (@CurrentPage * @PageSize + 1)
--Select one page of data based on the record numbers above

SELECT * FROM #TempTable

WHERE ID > @FirstRec

AND

ID < @LastRec

AND

EmployerID = @EmployerID

AND Job_no = @Job_no

ORDER BY surname asc

--Return the total number of records available as an output parameter
SELECT @TotalRecords = COUNT(*) FROM Customers
GO

View 1 Replies View Related

Select Query For Custom Paging

May 23, 2007

 Hi,I
am working on this select query for a report on website users. The
resulting rows will be displayed in a datagrid with custom paging. I
want to fetch 100 rows each time. This is the simplified query,
@currpage is passed as a parameter. ________________________________________________________________________________DECLARE @table TABLE (rowid INT IDENTITY(1,1), userid INT)INSERT INTO @table (userid) SELECT userid FROM UsersSELECT T.rowid, T.userid, ISNULL(O.userid, 0)FROM @table TLEFT OUTER JOIN ( SELECT DISTINCT(userid) FROM orders)AS OON O.userid = T.useridAND T.rowid > ((@currpage-1) * 100) AND T.rowid <= (@currpage * 100)ORDER BY T.rowid________________________________________________________________________________If
I run this query it returns all the rows, not just the 100 rows
corresponding to the @currpage value. What am I doing wrong? (The
second table with left outer join is there as I need one field to
indicate whether the user has placed an order with us or not. If the
value is 0, the user has not placed any orders) Thanks. 

View 2 Replies View Related

Orthodromy Calcul With Custom Paging In Sql

May 16, 2005

***the sql-instruction has been modified a lot, so whas was written here is now useless***

View 8 Replies View Related

Custom Paging - Getting A Subset From 2 Tables By UserID

Apr 7, 2008

I am trying to implement custom paging. I want to get a subset from my Threads and Post tables by userID. But I can't make the stored proc work. Could somebody have a look at this and tell me what I am doing wrong or if there is a better way of doing this?

ALTER PROCEDURE [dbo].[syl_ThreadPost_GetSubsetSortedByUserID2]

@UserID uniqueidentifier,

@sortExpression nvarchar(64),

@startRowIndex int,

@maximumRows int

AS

BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from

-- interfering with SELECT statements.

SET NOCOUNT ON

BEGIN TRY

IF LEN(@sortExpression) = 0

SET @sortExpression = 'PostID'

-- Since @startRowIndex is zero-based in the data Web control, but one-based w/ROW_NUMBER(), increment

SET @startRowIndex = @startRowIndex + 1

-- Issue query

DECLARE @sql nvarchar(4000)

SET @sql = 'SELECT t.[ThreadName],

p.PostID,

p.[PostTypeID],

p.[LanguageID],

p.[PostAccessID],

p.[UserID],

p.[ThreadID],

p.[PostParentID],

p.[VoteSummaryID],

p.[Subject],

p.[Body],

p.[PostAuthor],

p.[PostDate],

p.[IsApproved],

p.[TotalViews],

p.[FormattedBody],

p.[IPAddress],

p.[PostCount],

p.[ArticleCount],

p.[TrackbackCount],

p.[IsSticky],

p.[StickyDate]

FROM

(SELECT t.[ThreadName],

p.PostID,

p.[PostTypeID],

p.[LanguageID],

p.[PostAccessID],

p.[UserID],

p.[ThreadID],

p.[PostParentID],

p.[VoteSummaryID],

p.[Subject],

p.[Body],

p.[PostAuthor],

p.[PostDate],

p.[IsApproved],

p.[TotalViews],

p.[FormattedBody],

p.[IPAddress],

p.[PostCount],

p.[ArticleCount],

p.[TrackbackCount],

p.[IsSticky],

p.[StickyDate],

ROW_NUMBER() OVER(ORDER BY ' + @sortExpression + ') AS RowNum

FROM syl_Threads t RIGHT OUTER JOIN syl_Posts p

ON t.[ThreadID] = p.[ThreadID])

WHERE t.[UserID] = ' + CONVERT(nvarchar(16), @UserID) + ' )

AS syl_ThreadPostInfo

WHERE RowNum BETWEEN ' + CONVERT(nvarchar(16), @startRowIndex) + ' AND (' + CONVERT(nvarchar(16), @startRowIndex) + ' + ' + CONVERT(nvarchar(16), @maximumRows) + ') - 1'

-- Execute the SQL query

EXEC sp_executesql @sql

RETURN

END TRY

BEGIN CATCH

--Execute LogError_Insert SP

EXECUTE [dbo].[syl_LogError_Insert];

--Being in a Catch Block indicates failure.

--Force RETURN to -1 for consistency (other return values are generated, such as -6).

RETURN -1

END CATCH

END

View 4 Replies View Related

Sorting On A Temporary Field With A Custom Paging Method

May 18, 2005

I've made another topic before concerning this problem, but since  it was really confusing, I will made one clearer (it was about orthodromic formula, in case you read it, but the problem change during the topic, so thats why im creating this new one too).
I have a stored procedure with custom pagin method inside, and I want to sort my records on a fields I create myself  (which will receive a different value for each record.)  Now, I want to sort on this temporary field.  And since this is a custom paging method I can choose between many page.  Now, for the first page, it sorts fine.  But when I choose a page above the first one, the sorting is not right (the results all are wrong). 
So my real question is: is it really possible to sort on a Temporary Field in a custom paging method (because I know I can do it without any problem on a real field from my table, it just doesnt work right when I try on a temporary field).  I tried to solve my problem with this little SQL instruction, but it didnt give me any result yet:
SELECT TOP 20 PK,  test = field_value FROM Table WHERE PK not in (SELECT TOP 10 ad_id FROM Table ORDER BY ?) ORDER BY ?
well thanks for taking the time to read this, any help woulb be appreciated.

View 17 Replies View Related

Better Method To Count Records In Custom Paging For SQL Server 2005

Jul 24, 2006

heres my problem, since I migrated to SQL-Server 2005, I was able to use the Row_Number() Over Method to make my Custom Paging Stored Procedure better.  But theres onte thing that is still bothering me, and its the fact the Im still using and old and classic Count instruction to find my total of Rows, which slow down a little my Stored Procedure.  What I want to know is:  Is there a way to use something more efficiant to count theBig Total of Rows without using the Count instruction???  heres my stored procedure:
SELECT RowNum, morerecords, Ad_Id FROM (Select ROW_NUMBER() OVER (ORDER BY Ad_Id) AS RowNum, morerecords = (Select Count(Ad_Id) From Ads) FROM Ads)  as testWHERE RowNum Between 11 AND 20
The green part is the problem, the fields morerecords is the one Im using to count all my records, but its a waste of performance to use that in a custom paging method (since it will check every records, normally, theres a ton of condition with a lot of inner join, but I simplified things in my exemple)...I hope I was clear enough in my explication, and that someone will be able to help me.  Thank for your time.
  

View 1 Replies View Related

Automating A Custom Stored Procedure

Jul 13, 2000

Can I automate a stored procedure I made myself?
If so could someone kindly tell me how as I have tried to no avail.
Thanks in advnace

View 1 Replies View Related

Sql Stored Procedure With Custom Operators

Dec 29, 2007

Hi:

I am trying to create a stored procedure that filters some customers. The field in wich I am trying to apply the filter is the age field. The problem is that I need to be able to select the comparison operator =,<,>,=<,>=,<>.
I was trying to do it with the following code:

Select CustomerName From Customer Where
(CustomerAge & @Operator & @Age)

But sql Server shows an error telling me that @Operartor couldnt be converted to int.

I dont know if I am in the right track or way off, how is this done?

View 3 Replies View Related

Filtering A Custom Paged Stored Procedure

Oct 22, 2006

Hi,    I am trying to implement filtering on a custome paged stored Procedure, here is my curent Stored Procedure which doesn't error on complie or run but returns no records. Anyone got any ideas on how to make this work???<Stored Procedure>set ANSI_NULLS ONset QUOTED_IDENTIFIER ONgo-- =============================================-- Author:        Peter Annandale-- Create date: 22/10/2006-- Description:    Get Filtered Names-- =============================================ALTER PROCEDURE [dbo].[proc_NAMEFilterPaged]     -- Add the parameters for the stored procedure here    @startRowIndex int,     @maximumRows int,    @columnName varchar(20),    @filterValue varchar(20)ASBEGIN    -- SET NOCOUNT ON added to prevent extra result sets from    -- interfering with SELECT statements.    SET NOCOUNT ON;SELECT CODE, LAST_NAME, Name, TYPE, NUMBER    FROM         (SELECT n.CODE, n.LAST_NAME, n.FIRST_NAME + '  ' + n.MIDDLE_NAME AS Name, nt.TYPE, f.NUMBER,            ROW_NUMBER() OVER(ORDER BY n.LAST_NAME) as RowNum        FROM dbo.NAME n             LEFT OUTER JOIN NAMETYPE nt ON n.NAME_TYPE = nt.NAME_TYPE            LEFT OUTER JOIN FUNERAL f ON n.CODE = f.DECEASED        WHERE @columnName LIKE @filterValue        ) as NameInfo    WHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) -1END </Stored Procedure> Any assistance would be greatly appreciated.. Regards..Peter. 

View 1 Replies View Related

Stored Procedure To Generate Custom ID For Each Asset

Jan 7, 2012

I need creating a store procedure which generates custom IDs for each asset. I am programming for Fixed Assets in VB6 with SQL Server 2005. For example, when a new Asset is added ,I need to auto generate the ID based on existing IDs. New ID should not exist in tblAssets table.

Table Name : tblAssets
Fields : AssetID > Int,Primary Key,this is internal ID (identity seed)
AssetExtID >nvarchar(50),this is external ID, need to generate/user entered.

Below is the example of data in tblAssets :

AssetID AssetExtID ProjectID ItemName Qty UOM UnitCost .....
1 PROSP-00001 PROSPERITY SPLIT-AC 2 NOS $200
2 PROSP-00002 PROSPERITY LAPTOP 1 NOS $500
3 UNIII-00001 UNION III LAPTOP 5 NOS $400
4 UNIII-00002 UNION III RECEIVER 2 NOS $312

The AssetExtID depends on the ProjectID which is in tblProjects.

I will take care of the first 5 characters to generate. But the number part I need to generate by checking existing data. The AssetExtID should not be duplicate. Its unique for each asset.

View 4 Replies View Related

Custom Data Types In A Stored Procedure

Jun 12, 2008

I am new to working with custom data types. I am trying to use one as an input parameter for a stored procedure, but I'm not sure what the syntax is.

I the design table view, the data type shows up as this:
DISPOSAL_AREA_NAME_TYPE:varchar(40)

What is the proper way to reference it in a stored procedure? Here is what I have, but it errors out:
CREATE PROCEDURE webservices_BENEFICIAL_USES_DM_SELECT
@DISPOSAL_AREA_NAME [DISPOSAL_AREA_NAME_TYPE:varchar(40)] = ""
AS
BEGIN

View 4 Replies View Related

SqlDataSource Custom SQL Statement Vs Stored Procedure Permission Problem

May 8, 2008

PLEASE PLEASE PLEASE......
I did not get a single response for the last 6 hours... And during this time I was searching and trying to understand the problem but I am really stuck. If this is the wrong forum to ask this question, please redirect me. Really begging for replies...[:'(]
If I use the custom SQL statements in SqlDataSource, the application runs fine within the development environment (VS2005) but errors out if I publish the web site and access outside of the environment. In order to find-out the problem, I made the following test:
I created a select statement in one SqlDataSource to fill-in a GridView. I used the exact same statement to create a stored procedure and used that SP in second SqlDataSource and I fill a second GridView. When I debug or run the application, both grids are filled OK and everything works fine. However, when I publish the web site and try to do same only the stored procedure works fine and when I try to fill the grid using the built-in SQL, the page gives error. The error mesage is as follows when I use the address 'localhost':
Server Error in '/' Application.


The SELECT permission was denied on the object 'Contacts', database 'Homer', schema 'dbo'.
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.Data.SqlClient.SqlException: The SELECT permission was denied on the object 'Contacts', database 'Homer', schema 'dbo'.Source Error:



An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace:



[SqlException (0x80131904): The SELECT permission was denied on the object 'Contacts', database 'Homer', schema 'dbo'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +859322.......da da da .......
If I access the page using the IP address the message chages to below but it is not the issue, I just give it if it helps to find the problem:
Server Error in '/' Application.


Runtime Error
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine. Details: To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors> tag within a "web.config" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its "mode" attribute set to "Off". 
My SqlDataSource s are like this: <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:HomerConnectionString %>"
SelectCommand="TestRemoteAccess" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="TextBox1" Name="Param1" PropertyName="Text" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:HomerConnectionString %>"
SelectCommand="SELECT FirstName, LastName, Business FROM Contacts WHERE (ContactID = @Param1)">
<SelectParameters>
<asp:ControlParameter ControlID="TextBox2" Name="Param1" PropertyName="Text" />
</SelectParameters>
</asp:SqlDataSource>

 
 Environment: SQL Server 2005, VS2005, Vista
 

View 1 Replies View Related

Replicating Tables With An Identity Column Fails Even With Custom Stored Procedure

Mar 28, 1999

When replicating a table which has an identity column I get the error: "Procedure cp_insert_tblname expects parameter @C1, which was not supplied.". The stored procedure appears to be called without any parameters so my insert stored procedure does not work. I know I'm missing something basic here!! Do I have to add the field names when telling replication to use a custom stored procedure. If not, how do arguments get passed to my SP, as globals somehow?

Any info greatly appreciated!!
Thanks,
Jay

View 1 Replies View Related

Stored Procedure Based Custom Conflict Resolver Truncates Data

May 17, 2007

I created a stored procedure based custom conflict resolver in SQL 2005, I return the winning result set and also save that result set to a test table to compare the values. The values saved to the test table are correct but some of the values saved as the conflict winter are truncated.

Example a char(3) filed is updated at the subscriber as €˜111€™ and updated at the publisher as €˜222€™, in my custom conflict resolver if I use the value from the subscriber the conflict resolver updates the field as €™11 €˜, if I use the publisher value the conflict resolver updates the field as €™22 €˜. Now the same records is saved to the test table correctly as either €˜111€™ or €˜222€™ depending on the logic I used. So the result set has the correct values, its after the custom conflict resolver is called where the values is somehow truncated. Has anybody run into this before and what steps can I take to avoid this.

Thank you,
Pauly C

View 1 Replies View Related

Create Store Procedure To Paging!!!

Aug 27, 2007

Hi All!
I have Store Procedure:
If exists(Select * From sysobjects Where Name like 'Forum_Topic_SelectFromForum') Drop Procedure Forum_Topic_SelectFromForumgoCREATE PROCEDURE Forum_Topic_SelectFromForum( @ForumID varchar(10))
AS BEGIN TRANSACTIONSELECT * from Forum_Topic where ForumID=@ForumID Order by Tmp DESCIF @@ERROR <> 0 ROLLBACK TRANSACTIONELSE COMMIT TRANSACTION
Now, I want to Add 2 Variables: @Offset int, @Count int . With @Offset: the point of data, @Count: sum of row will get.
when get data I want it get from @Offset to Added @Count.
Help me to rewrite this store procedure. Thanks
 

View 2 Replies View Related

Sql 2005 Paging By Column In Procedure

Apr 23, 2008

Hi,

I've got some procedure which pages select query, the example is below:



Code Snippet
CREATEEND PROC GetCustomersByPage

@PageSize int, @PageNumber int

AS

Declare @RowStart int
Declare @RowEnd int

if @PageNumber > 0
Begin

SET @PageNumber = @PageNumber -1

SET @RowStart = @PageSize * @PageNumber + 1;
SET @RowEnd = @RowStart + @PageSize - 1 ;

With Cust AS
( SELECT CustomerID, CompanyName, CompanyAddress,
ROW_NUMBER() OVER (order by CompanyName) as RowNumber
FROM Customers )

select *
from Cust
Where RowNumber >= @RowStart and RowNumber <= @RowEnd end

How can I change this procedure in order to page the query OVER the column set as an argument?
In other words I would like to execute proc like:
- exec GetCustomersByPage 10, 1, 'CompanyName' which pages by CompanyName(...OVER (order by CompanyName)...)
- exec GetCustomersByPage 10, 1, 'CompanyAddress' which pages by ComanyAddress

Is it possible?

View 8 Replies View Related

Implementing Paging Using Store Procedure

Mar 19, 2007

Hi All,

I am using store procedure to which we pass ...

1.Sql query (String)
2.Starting index (Integer)
3.Page size (Integer)
4.total records out (Integer)

It works fine for the simple queries like "select * from tblcountry" but give error in case when we have sort of inline query or order clause or some complex query etc.

Despite of what is happing in the procedure can any help  me out with a simple store procedure to which i give any query , start index  and page size it should give me record set according to the given page.

For example query could be 'Select * from tblcountry where countryid in (select * from tblteachers) order by countryname desc', start index=0 , page size is 100 and total records are 500.

Note:
When i pass this query to sql server directly using command object its exectued successfully (this mean that it will also run fine in query analyzer), but i want to use paging in sql server so that is why i need a procedure to implement paging and query could be any its fully dynamic but i will be a valid query.

Your help in this regard is realy apperciated...

 

View 10 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

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

T-SQL (SS2K8) :: One Stored Procedure Return Data (select Statement) Into Another Stored Procedure

Nov 14, 2014

I am new to work on Sql server,

I have One Stored procedure Sp_Process1, it's returns no of columns dynamically.

Now the Question is i wanted to get the "Sp_Process1" procedure return data into Temporary table in another procedure or some thing.

View 1 Replies View Related

SQL Server 2014 :: Embed Parameter In Name Of Stored Procedure Called From Within Another Stored Procedure?

Jan 29, 2015

I have some code that I need to run every quarter. I have many that are similar to this one so I wanted to input two parameters rather than searching and replacing the values. I have another stored procedure that's executed from this one that I will also parameter-ize. The problem I'm having is in embedding a parameter in the name of the called procedure (exec statement at the end of the code). I tried it as I'm showing and it errored. I tried googling but I couldn't find anything related to this. Maybe I just don't have the right keywords. what is the syntax?

CREATE PROCEDURE [dbo].[runDMQ3_2014LDLComplete]
@QQ_YYYY char(7),
@YYYYQQ char(8)
AS
begin
SET NOCOUNT ON;
select [provider group],provider, NPI, [01-Total Patients with DM], [02-Total DM Patients with LDL],

[Code] ....

View 9 Replies View Related

Connect To Oracle Stored Procedure From SQL Server Stored Procedure...and Vice Versa.

Sep 19, 2006

I have a requirement to execute an Oracle procedure from within an SQL Server procedure and vice versa.

How do I do that? Articles, code samples, etc???

View 1 Replies View Related

Displaying Custom Properties For Custom Transformation In Custom UI

Mar 8, 2007

Hi,

I am creating a custom transformation component, and a custom user interface for that component.

In
my custom UI, I want to show the custom properties, and allow users to
edit these properties similar to how the advanced editor shows the
properties.

I know in my UI I need to create a "Property Grid".
In
the properties of this grid, I can select the object I want to display
data for, however, the only objects that appear are the objects that I
have already created within this UI, and not the actual component
object with the custom properties.

How do I go about getting the properties for my transformation component listed in this property grid?

I am writing in C#.

View 5 Replies View Related

Grab IDENTITY From Called Stored Procedure For Use In Second Stored Procedure In ASP.NET Page

Dec 28, 2005

I have a sub that passes values from my form to my stored procedure.  The stored procedure passes back an @@IDENTITY but I'm not sure how to grab that in my asp page and then pass that to my next called procedure from my aspx page.  Here's where I'm stuck:    Public Sub InsertOrder()        Conn.Open()        cmd = New SqlCommand("Add_NewOrder", Conn)        cmd.CommandType = CommandType.StoredProcedure        ' pass customer info to stored proc        cmd.Parameters.Add("@FirstName", txtFName.Text)        cmd.Parameters.Add("@LastName", txtLName.Text)        cmd.Parameters.Add("@AddressLine1", txtStreet.Text)        cmd.Parameters.Add("@CityID", dropdown_city.SelectedValue)        cmd.Parameters.Add("@Zip", intZip.Text)        cmd.Parameters.Add("@EmailPrefix", txtEmailPre.Text)        cmd.Parameters.Add("@EmailSuffix", txtEmailSuf.Text)        cmd.Parameters.Add("@PhoneAreaCode", txtPhoneArea.Text)        cmd.Parameters.Add("@PhonePrefix", txtPhonePre.Text)        cmd.Parameters.Add("@PhoneSuffix", txtPhoneSuf.Text)        ' pass order info to stored proc        cmd.Parameters.Add("@NumberOfPeopleID", dropdown_people.SelectedValue)        cmd.Parameters.Add("@BeanOptionID", dropdown_beans.SelectedValue)        cmd.Parameters.Add("@TortillaOptionID", dropdown_tortilla.SelectedValue)        'Session.Add("FirstName", txtFName.Text)        cmd.ExecuteNonQuery()        cmd = New SqlCommand("Add_EntreeItems", Conn)        cmd.CommandType = CommandType.StoredProcedure        cmd.Parameters.Add("@CateringOrderID", get identity from previous stored proc)   <-------------------------        Dim li As ListItem        Dim p As SqlParameter = cmd.Parameters.Add("@EntreeID", Data.SqlDbType.VarChar)        For Each li In chbxl_entrees.Items            If li.Selected Then                p.Value = li.Value                cmd.ExecuteNonQuery()            End If        Next        Conn.Close()I want to somehow grab the @CateringOrderID that was created as an end product of my first called stored procedure (Add_NewOrder)  and pass that to my second stored procedure (Add_EntreeItems)

View 9 Replies View Related







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