How To Construct Dynamic Sql In Stored Procedure

Jul 30, 2007

Hi Guys.

I want to construct a SQL in stored procedure in the following way. Please guide me how to achive this



CREATE PROCEDURE P_SAMPLE

(

@P_ONE NVARCHAR(240)

)

AS

BEGIN

DECLARE

@TMP_CNT INT

BEGIN

EXEC ('SELECT @TMP_CNT = 1')

-- PRINT @TMP_CNT

END

END



Regards
Mani


View 2 Replies


ADVERTISEMENT

How Do You Construct A Dynamic Stored Procedure With More Than 4000 Chars

Sep 12, 2007

My problem (excuse me for being a novice) is that whenever the query becomes complex
in the @whereclause (and it does) it cant exceed the character limit of a nvarchar. Now if someone could shed some ligfht on this for me I would be
incredibly grateful. I have tried doing the exec(@var1 + @var2) but this did not seem to work.


I have included the stored procedure below.

ALTER PROCEDURE [dbo].[SearchTenderMultiRegions]
(
@whereclause nVarChar(MAX), --4000 chars
@PageIndex int,
@PageSize int
) AS



SET NOCOUNT ON;DECLARE @sql nvarChar(MAX)

SET @sql= 'SELECT * FROM (SELECT DISTINCT TOP (' + CONVERT(nvarchar(10),(@PageIndex*@PageSize))
SET @sql= @sql + ') ROW_NUMBER() OVER (ORDER BY Tenders.ID DESC)AS Row,

Tenders.ID,Tenders.Title,Address.Suburb,Tenders.ClosingDateTime,Tenders.IsApproved,Tenders.TendersSourceID, Tenders.SourceDate,
UserTracking.CreateUserID,UserTracking.CreateDateTime FROM Tenders LEFT JOIN TenderContact ON Tenders.ID = TenderContact.TendersID
LEFT JOIN TenderCategory ON Tenders.ID = TenderCategory.TendersID
LEFT JOIN TenderRegion ON Tenders.ID = TenderRegion.TendersID
LEFT JOIN RegionStateCountry ON TenderRegion.RegionStateCountryID = RegionStateCountry.ID
LEFT JOIN Address ON Tenders.ID = Address.TendersID
LEFT JOIN UserTracking ON Tenders.ID = UserTracking.TendersID
WHERE '

SET @sql= @sql + @whereclause
SET @sql = @sql + ') as TenderSearchEntries
WHERE Row between ('

SET @sql= @sql + CONVERT(nvarchar(10), @PageIndex)
SET @sql= @sql + ' - 1) * '
SET @sql= @sql + CONVERT(nvarchar(10), @PageSize)
SET @sql= @sql + '+ 1 and '
SET @sql= @sql + CONVERT(nvarchar(10), @PageIndex)
SET @sql= @sql + ' * '
SET @sql= @sql + CONVERT(nvarchar(10), @PageSize)

EXEC(@sql)

View 5 Replies View Related

Best Way To Construct Dynamic Queries

Apr 17, 2008

I am working with a form that I wish to construct a dynamic query from the results of. The forum has a date range and two radio buttons. Each radio button enables a list of items that can be clicked. So for example, if we assume the question,

"What is your favorite food, and what toppings do you like on it?" where the radio buttons are foods, the list boxes are toppings. Assuming the user can choose a Hamburger or a Salad with generic toppings, their choices are as such:

They can choose a Hamburger, with every topping
They can choose a Hamburger with a single topping.
They can choose a Hamburger with multiple toppings.
They can choose a Salad with the same combinations as above.
They cannot choose both a Hamburger and a Salad - mutually exclusive items.

Then, I wish to construct a query that, based on the conditions above, retrieves information relavent to their criteria, such a the number of food items to choose from, their price, etc. - basic information. What is the most efficient way to do this? Should I write a stored procedure with numerous conditionals and all available parameters, constructing the sproc as such:





Code Snippet

CREATE PROCEDURE GetFoodInfo
@from datetime,
@to datetime,
@FoodType varchar(20),

@toppings varchar(20)

AS

BEGIN
DECLARE @query varchar(300)
SET @query = 'SELECT COUNT(DISTINCT ' + @FoodType + ') '


IF @FoodType = 'Hamburger'
SET @query = @query + 'FROM Hamburgers '

ELSE
SET @query = @query + 'FROM Salads '

IF @toppings <> 'ALL'

SET @query = @query ' WHERE Toppings = ' + @toppings



EXEC (@query)

Apologies of this syntax is incorrect, but you get the general idea. Of course, this is a small example - in reality, I would have 5-10 conditional requirements Or, should I generate a stored procedure (or simple query) for each operation? For example, assuming each is a stored procedure:

GetHamburgers <-- would get Hamburgers with all toppings
GetHamburgersWithToppings
GetSalads
GetSaladsWithToppings

What is the best method for what I wish to achieve? What is fastest? Is there a better way than I have listed? Thank you.

Again, this is a small example, but I hope someone can help.

View 3 Replies View Related

SQL Server 2012 :: Executing Dynamic Stored Procedure From A Stored Procedure?

Sep 26, 2014

I have a stored procedure and in that I will be calling a stored procedure. Now, based on the parameter value I will get stored procedure name to be executed. how to execute dynamic sp in a stored rocedure

at present it is like EXECUTE usp_print_list_full @ID, @TNumber, @ErrMsg OUTPUT

I want to do like EXECUTE @SpName @ID, @TNumber, @ErrMsg OUTPUT

View 3 Replies View Related

Multiple Stored Procedure...or 1 Dynamic Procedure?

Jul 3, 2007

Ok, so i have this program, and at the moment, it generates an sql statement based on an array of db fields, and an array of values...

my question is this, is there any way to create a stored procedure that has multiple dynamic colums, where the amount of colums could change based on how many are in the array, and therefore passed by parameters...

if this is possible, is it then better the pass both columns and values as parameters, (some have over 50 columns)...or just create a seperate stored procedure for each scenario?? i have no worked out how many this could be, but there is 6 different arrays of colums, 3 possible methods (update, insert and select), and 2 options for each of those 24...so possibly upto 48 stored procs...

this post has just realised how deep in im getting. i might just leave it as it is, and have it done in my application...

but my original question stands, is there any way to add a dynamic colums to a stored proc, but there could be a different number of colums to update or insert into, depending on an array??

Cheers,
Justin

View 2 Replies View Related

How To Construct The Query In Stored Proc

Jun 20, 2005

Hi,In the past I build up the query string within VB.NET page and easy to add the filtering statements in the SQL statement since it is just a string. For example, if user selected an option then include it in the filter, otherwise, just return all rows from table:Codes in ASPX.VB:   Dim SQL as String="SELECT * From Table1"   IF UserOption <> Null then      SQL = SQL & " WHERE Column1=" UserOption"   End ifNow, since I have a complicated page which need to use Stored Procedure to manapulate a temporary table before the final result. But I found when I want to add some user options similar to above, I found I don't know how to do it in Stored Procedure. In the Stored Procedure Property screen, I can't insert a IF..THEN statement within a SELECT statement. Seems I can only check the user option first and then determine the SELECT statement to use. That is: IF UserOption THEN SELECT statement 1 ELSE SELECT statement 2.But it is impossible for me to do this way since I'm not only one user option on the page. User usually can have several filters/selections on his screen. So if check which user option(s) are selected and write a static SELECT statement for it, I will have to program a complicated store procedure to cater all combinations for all user options (where some options may be null).Hope you can understanding what my mean and give me advices.Regards,Raymond

View 8 Replies View Related

HELP On Construct Of Update Stored Proc. .. THANKS!!!

Nov 6, 1998

Referencing the sample stored procedure
below that updates table 'this_table' containing
3 INT columns: 'key', 'col2', 'col3'.

How do I revise the stored procedure so that *** I do not
have to specify ALL the columns *** to update just one column?

e.g. if I want to update @col3 to 9 (exec sp_update_table, @col3 = 9),
how can I set col2 to its existing value?

create proc sp_update_table
@key int,
@col2 int,
@col3 int
as
update this_table
set col2 = @col2,
col3 = @col3
where key = @key
go

View 1 Replies View Related

Dynamic Where In Stored Procedure Help

Sep 7, 2004

Hi all,

I have a web application that has a search engine that returns records based off what the user selects in the search engine. I am currently using coalesce in the where statement in my stored procedure to return the records. For eample,
where field1= coalesce(@parm1,field1). I don't know if this example is better than building the sql statement dynamically in a parameter then executing the parameter with sp_executesql. Can someone explain to me which is better or if there is a better solution?

Thanks,

James

View 5 Replies View Related

Stored Procedure With Dynamic Sql

Aug 6, 2004

CREATE PROCEDURE ggg_test_sp
@start_date datetime,@end_Date datetime
AS

SET NOCOUNT ON
DECLARE @sqlstmt varchar(1000)

SELECT @sqlstmt='SELECT * FROM ggg_emp WHERE date_join BETWEEN ' +CONVERT(varchar(10),@start_date-1,101) + ' AND ' +CONVERT(varchar(10),@end_Date+1,101)

SELECT @sqlstmt
EXEC (@sqlstmt)

GO


I want to apply date filter in the above sp with dynamic sql stmt. When i execute the above procedure with date ranges( @start_date=07/06/2004 AND @end_Date= 08/06/2004)i am not getting any result because my @sqlstmt variable has the select stamet

SELECT * FROM ggg_emp WHERE date_join BETWEEN 07/06/2004 AND 08/06/2004

BUT it should have the sqlstmt as

SELECT * FROM ggg_emp WHERE date_join BETWEEN '07/06/2004' AND '08/06/2004' to produce the required result

I know that for the above SP we dont need any dynamic sql but this is just an example.

So anyone can help me on this issue.

Thanks.

View 1 Replies View Related

Dynamic WHERE In Stored Procedure

Sep 29, 2007

Can anyone help me with this dumb question?
I want to use a stored procedure to bring back a recordset depending if a bit column is set to 1. My table has a number of columns that are of Data Type bit and I want to be able to specify which particular column I'm interested in as a parameter when I call the Stored Procedure.

I have set up the Stored Procedure as follows:


CREATE PROCEDURE getProducts
@param1 varchar(50)
AS
SELECT ProductID, ProductName
FROM dbo.Products
WHERE @param1 = '1'
GO


I'm calling it like this:


Dim cmdX, cmdParam, rsX
cmdParam = "OnSpecial"

set cmdX = Server.CreateObject("ADODB.Command")
cmdX.ActiveConnection = conn_STRING
cmdX.CommandText = "dbo.getProducts"
cmdX.Parameters.Append cmdX.CreateParameter("@RETURN_VALUE", 3, 4)
cmdX.Parameters.Append cmdX.CreateParameter("@param1", 200, 1,50,cmdParam)
cmdX.CommandType = 4
cmdX.CommandTimeout = 0
cmdX.Prepared = true
set rsX = cmdX.Execute
rsX_numRows = 0


I know for a fact that I have products in my dbase with the bit column 'OnSpecial' set to 1, yet no records are coming back.

Any pointers would be most appreciated.

View 3 Replies View Related

Help With Dynamic SQL Stored Procedure

Jul 23, 2005

I have a stored procedure spGetAccessLogDynamic and when I try to callit I get the following error:Server: Msg 2812, Level 16, State 62, Line 1Could not find stored procedure 'S'.I dont know why because I dont have anything refering to storedprocedure 'S'I have ran my SQL String with sample values and it works fine. So Iam presuming that it is some kind of syntax error in my storedprocedure but have tried everything and cant find it!Anyway here is the sample data I am using to call it and my spExec spGetAccessLogDynamic '24', '2005/07/04 00:00:00 AM', '2005/11/0400:00:00 AM', 'TimeAccessed DESC'CREATE PROCEDURE spGetAccessLogDynamic(@PinServiceID varchar (4),@StartDate varchar(40),@EndDate varchar(40),@SortExp varchar (100))AS-- Create a variable @SQL StatementDECLARE @SQLStatement varchar-- Enter the Dynamic SQL statement into the variable @SQLStatementSELECT @SQLStatement = ( 'SELECT A.PinValue,A.TimeAccessed,C.Forename, C.SurnameFROM AccessLog A, Members C, Pins PWHERE P.PinValue = A.PinValue ANDP.MemberID = C.MemberID AND A.PinServiceID= ''' + @PinServiceID + '''AND A.TimeAccessed BETWEEN dbo.func_DateMidnightPrevious( ''' +@StartDate + ''' ) AND dbo.func_DateMidnightNext( ''' + @EndDate+''')GROUP BY A.PinValue,A.TimeAccessed, C.Forename, C.SurnameORDER BY ' + @SortExp)-- Execute the SQL statementEXEC ( @SQLStatement)GOAny help would be very very much appreciated!!!!!!ThanksCaro

View 2 Replies View Related

Dynamic SQL Stored Procedure

Dec 4, 2007



We are continuing to have issues with a certain stored procedure using dynamic sql. The issue arose when we tried to clean the stored procedure up, and seemed to have zero problems in staging. As soon as we moved it into production, the stored proc caused excessive blocking and completely slowed down our production environment. We immediately rolled back the older version and production is back to normal.

After looking at the new procedure I don't understand how it could cause blocking. Any help is much appreciated!

Old Proc without issues----
--------
USE [Realist_Prod_1203]
GO
/****** Object: StoredProcedure [dbo].[USP_GetMatchedMLSRecord] Script Date: 12/04/2007 09:33:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/*
=====================
Created By: Sunil/Sudeep 19-11-2003
Description:
Does a lookup of MLS Property data for reverse link. This is susceptible to error in that if erroneous data is given
to us,it will not find a match. For this reason, commented out the lookup on Suffix and changed the street
to use a like clause. Many users are putting the suffix in the street clause and no hits are generated.
This hurts performance, but it improves the hit ratio.

Usage: exec USP_GetMatchedMLSRecord 61,'3951','','KENSINGWOOD','DR','3951','columbus','OH','43230','39049','600-260368','600-260368-00','6000260368','urlll'

Mods:
01/08/2004 - Balawant - Added nullif(), as it was comparing apn numbers with '' (empty space)
02/23/2004 - Balawant - Added or (or State = '') condition for state, zip, city, StreetDirection and Suffix.
11/18/2004 - Sunil Padmanbhan - Added begin-end and modified altapn and parcelid in nullif statment.
04/03/2007 - Shiny - changed to Parameterized query generation
04/03/2007 - Vasan - Removed redundant nullif's and added a limit of 100 records on output
04/03/2007 - Shiny - Removed more Nullif's and changed datatypes for Zip and CountyID to Char to match with table datatypes
04/05/2007 - Vasan - Modified to match resultsets with original procedure
=====================
if exists (select 1 from sysobjects where name = 'USP_GetMatchedMLSRecord')
drop procedure USP_GetMatchedMLSRecord
grant exec on USP_GetMatchedMLSRecord to webuser
*/
CREATE PROCEDURE [dbo].[USP_GetMatchedMLSRecord]
(
@GroupID int,
@HouseNumber varchar(50),
@StreetDirection varchar(50),
@StreetName varchar(50),
@Suffix varchar(50),
@Unit varchar(50),
@City varchar(50),
@State varchar(50),
@ZIP char(50),
@FIPS varchar(10),
@ApnNumber varchar(50),
@AltApn varchar(50),
@ParcelId varchar(50),
@ReverseLinkURL varchar(200)
)
AS
DECLARE @CountyID char(6)
Select @CountyID=CountyID from ltCounties where FIPS=@FIPS
IF (@ApnNumber IS NOT NULL AND @ApnNumber <> '') AND (EXISTS (SELECT 1 FROM tblMLSListing WITH (NOLOCK) WHERE APNnumber=@ApnNumber AND GroupID=@GroupID ))
SELECT @ReverseLinkURL as 'ReverseLinkBaseURL', MLSNumber,Comment FROM tblMLSListing WITH (NOLOCK)
WHERE APNnumber=@ApnNumber AND GroupID = @GroupID ;
ELSE
BEGIN
IF (@AltApn IS NOT NULL AND @AltApn <> '') AND (EXISTS (SELECT 1 FROM tblMLSListing WITH (NOLOCK) WHERE APNnumber=@AltApn AND GroupID=@GroupID))
SELECT @ReverseLinkURL as 'ReverseLinkBaseURL', MLSNumber,Comment FROM tblMLSListing WITH (NOLOCK)
WHERE APNnumber= @AltApn AND GroupID=@GroupID;
ELSE
IF (@ParcelId IS NOT NULL AND @ParcelId <> '') AND (EXISTS (SELECT 1 FROM tblMLSListing WHERE APNnumber=@ParcelId AND GroupID=@GroupID ))
SELECT @ReverseLinkURL as 'ReverseLinkBaseURL', MLSNumber,Comment FROM tblMLSListing WITH (NOLOCK)
WHERE APNnumber= @ParcelId AND GroupID=@GroupID;
ELSE
BEGIN
-- Finalize parameter values
IF @ReverseLinkURL IS NULL SET @ReverseLinkURL = '';
IF @StreetName IS NOT NULL AND @StreetName <> '' SET @StreetName = @StreetName + '%';
-- Build up SQL text dynamically, only including filter predicates for those parameters that the user wants
-- to search on.
DECLARE @sqltext nvarchar(4000)
SET @sqltext = 'Select top 100 '''' + @ReverseLinkURL as ''ReverseLinkBaseURL'',MLSNumber,Comment
from tblMLSListing WITH (NOLOCK)
where '
-- Because of skew and relative few group IDs, you may want to use an inline literal for this one parameter
-- to avoid plan sharing across different GroupIDs. Use explicit parameterization for the other parameters.
if @GroupID is null set @sqltext = @sqltext + '1=1' --ignore Group_ID if null
else SET @sqltext = @sqltext + 'GroupID=' + CONVERT (varchar(30), @GroupID) + ' ' ;
--House number is mandatory: IF @HouseNumber IS NOT NULL AND @HouseNumber <> ''
SET @sqltext = @sqltext + ' AND HouseNumber=@HouseNumber '
IF @StreetDirection IS NOT NULL AND @StreetDirection <> '' SET @sqltext = @sqltext + ' AND (StreetDirection=@StreetDirection or @StreetDirection='''') '
IF @StreetName IS NOT NULL AND @StreetName <> '' SET @sqltext = @sqltext + ' AND StreetName like @StreetName '
IF @Suffix IS NOT NULL AND @Suffix <> '' SET @sqltext = @sqltext + ' AND (Suffix=@Suffix or Suffix='''') '
--Unit is mandatory: IF @Unit IS NOT NULL AND @Unit <> ''
SET @sqltext = @sqltext + ' AND Unit=@Unit '
IF @City IS NOT NULL AND @City <> '' SET @sqltext = @sqltext + ' AND (City=@City or City='''') '
IF @State IS NOT NULL AND @State <> '' SET @sqltext = @sqltext + ' AND (State=@State or State='''') '
IF @ZIP IS NOT NULL AND @ZIP <> '' SET @sqltext = @sqltext + ' AND (ZIP=@ZIP or ZIP='''') '
--CountyId is mandatory: IF @CountyID IS NOT NULL AND @CountyID <> ''
SET @sqltext = @sqltext + ' AND CountyID=@CountyID '
-- Execute as an explicitly parameterized query. This will provide plan reuse for any executions of the proc
-- that have the same @GroupID and the same combination of non-empty parameters.
/*print @sqltext
print '@ReverseLinkURL = ' + @ReverseLinkURL
print '@HouseNumber = ' + @HouseNumber
print '@StreetDirection = ' + @StreetDirection
print '@StreetName = ' + @StreetName
print '@Suffix = ' + @Suffix
print '@Unit = ' + @Unit
print '@City = ' + @City
print '@State = ' + @State
print '@ZIP = ' + @ZIP
print ' @CountyID = ' + @CountyID
print 'debug: ApnNumber = ' + @ApnNumber*/

EXEC sp_executesql
@sqltext,
N'@ReverseLinkURL varchar(200), @HouseNumber varchar(50), @StreetDirection varchar(50), @StreetName varchar(50),
@Suffix varchar(50), @Unit varchar(50), @City varchar(50), @State varchar(50), @ZIP varchar(50), @CountyID varchar(50)',
@ReverseLinkURL=@ReverseLinkURL, @HouseNumber=@HouseNumber, @StreetDirection=@StreetDirection, @StreetName=@StreetName,
@Suffix=@Suffix, @Unit=@Unit, @City=@City, @State=@State, @ZIP=@ZIP, @CountyID=@CountyID
END
END

New Proc WITH Blocking issues----
--------
/*
=====================
Created By: David Barrs 8-13-2002
Description: Returns the properties for given group id

Usage:
EXEC USP_GetMatchedMLSRecord 1,'8108','','dunn','','','austin','TX','','48453','','','','http://sef.mlxchange.com/reverselink.asp?action=reverselink'
Mods:
xx/xx/xxxx - who - Description
11/28/2007 - Shiny - Refactored the procedure
\\\\\\
=====================
if exists (select 1 from sysobjects where name = 'USP_GetMatchedMLSRecord')
drop procedure USP_GetMatchedMLSRecord
grant exec on USP_GetMatchedMLSRecord to webuser
*/
ALTER PROCEDURE [dbo].[USP_GetMatchedMLSRecord]
(
@GroupID int,
@HouseNumber varchar(50),
@StreetDirection varchar(50),
@StreetName varchar(50),
@Suffix varchar(50),
@Unit varchar(50),
@City varchar(50),
@State varchar(50),
@ZIP char(50),
@FIPS varchar(10),
@ApnNumber varchar(50),
@AltApn varchar(50),
@ParcelId varchar(50),
@ReverseLinkURL varchar(200)
)
AS
DECLARE
@sqltext nvarchar(4000),
@paramlist nvarchar(4000),
@CountyID char(6)
Select @CountyID=CountyID from ltCounties where FIPS=@FIPS
IF (@ApnNumber IS NOT NULL AND @ApnNumber <> '') AND (EXISTS (SELECT 1 FROM tblMLSListing WITH (NOLOCK) WHERE APNnumber=@ApnNumber AND GroupID=@GroupID ))
SELECT @ReverseLinkURL as 'ReverseLinkBaseURL', MLSNumber,Comment FROM tblMLSListing WITH (NOLOCK)
WHERE APNnumber=@ApnNumber AND GroupID = @GroupID ;
ELSE
BEGIN
IF (@AltApn IS NOT NULL AND @AltApn <> '') AND (EXISTS (SELECT 1 FROM tblMLSListing WITH (NOLOCK) WHERE APNnumber=@AltApn AND GroupID=@GroupID))
SELECT @ReverseLinkURL as 'ReverseLinkBaseURL', MLSNumber,Comment FROM tblMLSListing WITH (NOLOCK)
WHERE APNnumber= @AltApn AND GroupID=@GroupID;
ELSE
IF (@ParcelId IS NOT NULL AND @ParcelId <> '') AND (EXISTS (SELECT 1 FROM tblMLSListing WHERE APNnumber=@ParcelId AND GroupID=@GroupID ))
SELECT @ReverseLinkURL as 'ReverseLinkBaseURL', MLSNumber,Comment FROM tblMLSListing WITH (NOLOCK)
WHERE APNnumber= @ParcelId AND GroupID=@GroupID;
ELSE
BEGIN
-- Finalize parameter values
IF @ReverseLinkURL IS NULL SET @ReverseLinkURL = '';
IF @StreetName IS NOT NULL AND @StreetName <> '' SET @StreetName = @StreetName + '%';
-- Build up SQL text dynamically, only including filter predicates for those parameters that the user wants
-- to search on.
SELECT @sqltext = 'Select top 100 '''' + @ReverseLinkURL as ''ReverseLinkBaseURL'',MLSNumber,Comment
from tblMLSListing WITH (NOLOCK)
where '
IF @GroupID IS NOT NULL
SELECT @sqltext = @sqltext + 'GroupID=' + CONVERT (varchar(30), @GroupID) + ' '

SELECT @sqltext = @sqltext + ' AND HouseNumber=@HouseNumber '

IF @StreetDirection IS NOT NULL
SELECT @sqltext = @sqltext + ' AND StreetDirection = @StreetDirection '

IF @StreetName IS NOT NULL
SELECT @sqltext = @sqltext + ' AND StreetName LIKE @StreetName + ''%'''

IF @Suffix IS NOT NULL
SELECT @sqltext = @sqltext + ' AND Suffix = @Suffix'

SELECT @sqltext = @sqltext + ' AND Unit=@Unit '

IF @City IS NOT NULL
SELECT @sqltext = @sqltext + ' AND City = @City'

IF @State IS NOT NULL
SELECT @sqltext = @sqltext + ' AND State = @State'

IF @ZIP IS NOT NULL
SELECT @sqltext = @sqltext + ' AND ZIP = @ZIP'
SELECT @sqltext = @sqltext + ' AND CountyID='+ CONVERT (varchar(30), @CountyID)+' '
SELECT @paramlist = '
@GroupID int,
@HouseNumber varchar(50),
@StreetDirection varchar(50),
@StreetName varchar(50),
@Suffix varchar(50),
@Unit varchar(50),
@City varchar(50),
@State varchar(50),
@ZIP char(50),
@FIPS varchar(10),
@ApnNumber varchar(50),
@AltApn varchar(50),
@ParcelId varchar(50),
@ReverseLinkURL varchar(200)'

/*
print '@ReverseLinkURL = ' + @ReverseLinkURL
print '@HouseNumber = ' + @HouseNumber
print '@StreetDirection = ' + @StreetDirection
print '@StreetName = ' + @StreetName
print '@Suffix = ' + @Suffix
print '@Unit = ' + @Unit
print '@City = ' + @City
print '@State = ' + @State
print '@ZIP = ' + @ZIP
print '@CountyID = ' + @CountyID
print 'debug: ApnNumber = ' + @ApnNumber
*/
EXEC sp_executesql @sqltext, @paramlist, @GroupID, @HouseNumber, @StreetDirection, @StreetName,
@Suffix, @Unit, @City, @State, @ZIP, @FIPS, @ApnNumber, @AltApn, @ParcelId, @ReverseLinkURL
END
END;


Thank You,

-D

View 1 Replies View Related

Permissions With Dynamic SQL Within Stored Procedure

Aug 1, 2006

Okay, I have sort of a peculiar permissions question I am wondering if someone can help me with. Basically, here's the scenario...
I have a CLR stored procedure which does some dynamic SQL building based on values sent in via XML. It's a CLR stored procedure using XML because I want to build a parameterized statement (to guard against SQL Injection) based on a flexible number of parameters which are basically passed in the XML.
The dynamic SQL ends up reading from a table I'll call TableX and I actually discovered an (understandable) quirk with security.
Basically, the connection context is using security for a low-privilaged Windows account ("UserX") and UserX has no permission to the table referenced in the dynamic SQL but because of the dyanmic nature of the query, the stored procedure ends up adopting the security context of UserX. Naturally, this throws a security exception saying UserX has no SELECT permission on TableX.
Now, I can give UserX read permission to the table in question to get things running, but one of the points of using stored procedures is to defer security to the procedure level vs. configuration for tables or columns.
So in striving toward my ideal of security at the procedure level, my question is what is the best way to allow minimum privilege in this case?
I thought about having the internals of the CLR stored procedure run under a different (low-privalaged) security context, but I am wondering if there's an alternate configuration that may be as secure, but simpler.
PS - Please don't let this degenerate into a conversation about OR mappers. I know that happens a lot on these forums.
 

View 3 Replies View Related

Run Dynamic Query Using Stored Procedure

Aug 16, 2007

Hi,
I need to create a stored procedure, which needs to accept the column name and table name as input parameter,
and form the select query at the run time with the given column name and table name..
my procedure is,
CREATE PROC spTest
@myColumn varchar(100) ,
@myTable varchar(100)
 AS
SELECT @myColumn FROM @myTable
GO
This one showing me the error,
stating that myTable is not declared..
.............as i need to perform this type of query for more than 10 tables.. i need the stored procedure to accept the column and table as parameters..
Plese help me?? Is it possible in stored procedure..
 
 
 
 

View 3 Replies View Related

Variables In Dynamic SQL In A Stored Procedure

Aug 23, 2007

I am taking my first steps into stored procedures and I am working on a solution for efficiently paging large resultsets with SQL Server 2000 based on the example on 4Guys: http://www.4guysfromrolla.com/webtech/042606-1.shtml
The problem with my stored procedure is, is that it doesn't seem to recognize a variable (@First_Id) in my dynamic Sql. With this particular sproc I get the error message: "Must declare the scalar variable '@First_Id'"It seems to be a problem with 'scope', though I still can't yet figure out. Can anyone give me some hints on how to correctly implement the @First_Id in my stored procedure? Thanks in advance!
Here's the sproc:
ALTER PROCEDURE dbo.spSearchNieuws(@SearchQuery NVARCHAR(100) = NULL,@CategorieId INT = NULL,@StartRowIndex INT,        @MaximumRows INT,@Debug BIT = 0)ASSET NOCOUNT ONDECLARE @Sql_sri   NVARCHAR(4000),@Sql_mr    NVARCHAR(4000),@Paramlist NVARCHAR(4000),@First_Id  INT, @StartRow  INTSET ROWCOUNT @StartRowIndexSELECT @Sql_sri = 'SELECT @First_Id = dbo.tblNieuws.NieuwsId FROM dbo.tblNieuwsWHERE 1 = 1'IF @SearchQuery IS NOT NULLSELECT @Sql_sri = @Sql_sri + ' AND FREETEXT(dbo.tblNieuws.Nieuwskop, @xSearchQuery)'              IF @CategorieId IS NOT NULLSELECT @Sql_sri = @Sql_sri + ' AND dbo.tblNieuws.CategorieId = @xCategorieId'SELECT @Sql_sri = @Sql_sri + ' ORDER BY dbo.tblNieuws.NieuwsId DESC'SET ROWCOUNT @MaximumRows SELECT @Sql_mr = 'SELECT dbo.tblNieuws.NieuwsId, dbo.tblNieuws.NieuwsKop, dbo.tblNieuws.NieuwsLink, dbo.tblNieuws.NieuwsOmschrijving, dbo.tblNieuws.NieuwsDatum,                 dbo.tblNieuws.NieuwsTijd, dbo.tblNieuws.BronId, dbo.tblNieuws.CategorieId, dbo.tblBronnen.BronNaam, dbo.tblBronnen.BronLink, dbo.tblBronnen.BiBu, dbo.tblBronnen.Video,                dbo.tblCategorieen.CategorieFROM       dbo.tblNieuws INNER JOIN                dbo.tblBronnen ON dbo.tblNieuws.BronId = dbo.tblBronnen.BronId INNER JOIN                dbo.tblCategorieen ON dbo.tblNieuws.CategorieId = dbo.tblCategorieen.CategorieId AND                 dbo.tblBronnen.CategorieId = dbo.tblCategorieen.CategorieId         WHERE dbo.tblNieuws.NieuwsId <= @First_Id          AND 1 = 1'               IF @SearchQuery IS NOT NULLSELECT @Sql_mr = @Sql_mr + ' AND FREETEXT(dbo.tblNieuws.Nieuwskop, @xSearchQuery)'           IF @CategorieId IS NOT NULLSELECT @Sql_mr = @Sql_mr + ' AND dbo.tblNieuws.CategorieId = @xCategorieId'     SELECT @Sql_mr = @Sql_mr + ' ORDER BY dbo.tblNieuws.NieuwsId DESC'IF @Debug = 1PRINT @Sql_mr  SELECT @Paramlist = '@xSearchQuery NVARCHAR(100),     @xCategorieId INT'EXEC sp_executesql   @Sql_sri, @Paramlist,     @SearchQuery, @CategorieIdEXEC sp_executesql   @Sql_mr, @Paramlist,     @SearchQuery, @CategorieId 

View 8 Replies View Related

Dynamic Query In Stored Procedure

Apr 22, 2008

Hi i am trying to make the "userName" section of the code below dynamic as well, how can i do this, the reason being userName will not always be passed through to it. 
 
ALTER PROCEDURE [dbo].[stream_UserFind]

@userName varchar(100),
@subCategoryID INT,
@regionID INT
)ASdeclare @StaticStr nvarchar(5000)set @StaticStr = 'SELECT DISTINCT SubCategories.subCategoryID, SubCategories.subCategoryName,Users.userName ,UserSubCategories.userIDFROM Users INNER JOIN UserSubCategories ON Users.userID= UserSubCategories.userIDINNER JOINSubCategories ON UserSubCategories.subCategoryID = SubCategories.subCategoryID WHERE UserName like ' + char(39) + '%' + @UserName + '%' + char(39)
if(@subCategoryID <> 0) set @StaticStr = @StaticStr + ' and SubCategories.subCategoryID  = ' + cast( @subCategoryID as varchar(10))if(@regionID <> 0) set @StaticStr = @StaticStr + ' and SubCategories.RegionId  = ' + cast( @regionID as varchar(10))
print @StaticStr
exec(@StaticStr)
)

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

Trying To Build Dynamic Stored Procedure

Jun 6, 2008

My existing ASP 1.0 site keeps getting hacked using SQL injections.  I have rewritten the site in ASP 3.5 to stop the attacks but cannot figure out how to dynamically generate a basic keyword search.
I am trying to take the keywords entered into an array and then construct the WHERE clause - not having much luck.  Getting either errors or double LIKE statements. Need some help.
string[] SqlKWSrch; 
SqlSrch = KWordSrch.Text;SqlKWSrch = SqlSrch.Split(' ', ',');     int AStop = SqlKWSrch.Length;     int i = 0;        foreach( string a in SqlKWSearch )       {           if (i <= AStop)           {               SqlWHR = SqlWHR + "L_Kwords LIKE '%' + " + " '" + SqlKWSrch[i] + "' " + " + '%' AND ";           }           else           {               SqlWHR = SqlWHR + "L_Kwords LIKE '%' + " + " '" + SqlKWSrch[i] + "' " + " + '%' ";           }            i++;       }
1) I can't seem to properly terminate the final LIKE statement2) can't figure out how to pass 'SqlWHR' to the procedure
GIVEN KEYWORDS: 'antique chairs' entered I want to end up with the below SP, the @SqlWHR parameter appeared to have worked once but it probably was an illusion.
PROCEDURE KeyWordSearch@SqlWHR varchar(100)AS
SELECT L_Name, L_City, L_State, L_Display FROM tblCompanies WHERE L_Kwords LIKE '%' + 'antique' + '%' AND L_Kwords LIKE '%' + 'chairs' + '%' AND L_Display = 1
RETURN
 
Thank you
 

View 5 Replies View Related

Dynamic Query In Stored Procedure

Jun 13, 2008

Hi, I have a table with values such as test1, test2, test3, test4, test5.
I need to write a stored procedure with paramater (number TINYINT, number2 TINYINT), the number represents the field that I'm going to select and compare. For example if I pass in (1,5) I will need the fields test1 and test5 and store them in Temp and Temp2. How do I write the following to so it will dynamically select which field to use when passing the parameters?
DECLARE @Temp TINYINT,
DECLARE @Temp2 TINYINT, 
SELECT top 1 Temp = test1, Temp2 = test5 from table

View 4 Replies View Related

Dynamic WHERE Clause To Stored Procedure

May 25, 2004

Hi all!
I need to create a stored procedure with a parameter and then send a WHERE clause to that parameter (fields in the clause may vary from time to time thats why I want to make it as dynamic as possible) and use it in the query like (or something like) this:

---------------------------------------------------
@crit varchar(100)

SELECT fldID, fldName FROM tblUsers
WHERE @crit
----------------------------------------------------

Of course this does not work, but I don't know how it should be done, could someone please point me in the right direction on how to do this kind of queries.

cheers!
pelle

View 2 Replies View Related

Dynamic ORDER BY Within Stored Procedure

Jul 7, 2004

I am trying to do something similar to the following where I want to perform dynamic ordering on two tables that have been unioned as shown below.


CREATE PROCEDURE procedure_name
@regNum varchar(14),
@sortOrder tinyint = 1
AS
SELECT Filler_OrdNum As 'Accession', RTrim(Obs_Code) As 'Observation', REG As 'Register',
Obs_Date As 'Observation Date'
FROM tblSPG_Header
WHERE
REG = @regNum
UNION
SELECT Filler_OrdNum As 'Accession', RTrim(Obs_Code) As 'Observation', REG As 'Register',
Obs_Date As 'Observation Date'
FROM tblRCH_Header
WHERE
REG = @regNum
ORDER BY Obs_Date DESC
GO


Note that I am only sorting on the Obs_Date column, but I'd like to be able to sort on any column within the selection list. I know that I need to use:


ORDER BY CASE WHEN @sortOrder = 1 THEN Obs_Date END DESC


but I frequently get the following error when I try to do so:

"ORDER BY items must appear in the select list if the statements contain a UNION operator"

If anyone can offer any suggestions, I would appreciate it. Thanks.

View 1 Replies View Related

Dynamic Where Clause In Stored Procedure

Jul 23, 2004

Hi, I have several parameters that I need to pass to stored procedure but sometimes some of them might be null. For example I might pass @Path, @Status, @Role etc. depending on the user. Now I wonder if I should use dynamic Where clause or should I use some kind of switch, maybe case and hardcode my where clause. I first created several stored procedures like Documents_GetByRole, Documents_GetByRoleByStatus ... and now I want to combine them into one SP. Which approach is better. Thanks for your help.

View 1 Replies View Related

Dynamic Stored Procedure Errors

Aug 17, 2004

Hi

I am getting the following error

Syntax error converting the varchar value 'Select * from Residential WHERE Price BETWEEN ' to a column of data type int.

when running the following SP.



CREATE PROCEDURE testing
(
@Locationnvarchar(100)=NULL,
@TypeHomenvarchar(50)=NULL,
@MinPriceint=0,
@MaxPriceint=9999999999,
@Bedroomsnvarchar(2)=NULL,
@BathsSearchnvarchar(2)=NULL
)
AS

Declare @strSql char(255)
Set @strSql="Select * from Residential WHERE "

Set @strSql=@strSql + "Price BETWEEN " + @MinPrice + " AND " + @MaxPrice
If @Location is NOT NULL
Set @strSql=@strSql + ' AND city = ' + @Location

If @TypeHome is NOT NULL
Set @strSql=@strSql + ' AND Type = ' + @TypeHome

Set @strSql=@strSql + ' AND BDRM >= ' + @Bedrooms
Set @strSql=@strSql + ' AND BATHS <= ' + @BathsSearch
Set @strSql=@strSql + ' AND IDX = Y'

Exec(@strSql)



What is causing this error?

Thanks in advance

View 3 Replies View Related

Problem In A Dynamic Stored Procedure---help

Sep 7, 2004

I create a stored procedure as following:
........

CREATE Procedure myAutoSearch
(
@Make varchar(50),
@Model varchar(50),
@AutoType varchar(50),
@Miles float,
@Zipcode varchar(5)
)
AS

DECLARE @RowCount int
SELECT @RowCount = Count(*) FROM ZIPCodes WHERE ZIPCode = @Zipcode AND CityType = 'D'

if @RowCount > 0
BEGIN

SELECT
z.ZIPCode, z.City, z.StateCode, a.Make, a.Model, a.AutoPrice, a.AutoPrice2, a.AutoYear,
a.Mileage, a.AdID, a.ImageURL, dbo.DistanceAssistant(z.Latitude,z.Longitude,r.Latitude,r.Longitude) As Distance
/*
The above functions requires the Distance Assistant.
*/
FROM
ZIPCodes z, RadiusAssistant(@ZIPCode,@Miles) r, AutoAd a
WHERE
z.Latitude <= r.MaxLat
AND z.Latitude >= r.MinLat
AND z.Longitude <= r.MaxLong
AND z.Longitude >= r.MinLong
AND z.CityType = 'D'
AND z.ZIPCodeType <> 'M'
AND z.ZIPCode = a.Zipcode
AND a.AdActive = '1'
AND a.AdExpiredate >= getdate()
AND a.Make = @Make
AND dbo.DistanceAssistant(z.Latitude,z.Longitude,r.Latitude,r.Longitude) <= @Miles
/*
The above functions requires the Distance Assistant.
Also note that SQL Server caches the results so that this and the "SELECT dbo.DistanceAssistant"
functions are both only computed once.
*/
ORDER BY Distance, Make

END
ELSE
SELECT -1 As ZIPCode
--ZIP Code not found...

....................

This stored procedure work very well.

The question is how I add some dynamic condition inside the where condition.

I want to add:

If @Model <> "See All Models"
AND a.Model = @Model'


If @AutoType <> "New/Used"
AND a.Condition = @AutoType

I try several ways, but fail.

If you know how to add these two dynamic parameters into the condition of stored procedure, please help.

View 9 Replies View Related

Building A Dynamic Stored Procedure

Mar 30, 2005

Hi

I am in the very final stages of
building a dating app for a client, I am totally stuck with the
advanced search page. been googling for days with limited success

For the most basic of purposes I have added a few form fields to my search.aspx page;
county (Dropdown list)
min age (Dropdown list)
max age (dropdown list)
Smoker (check box)
keyword (textbox)

My codebehind passes the vars to a stored procedure
@county = me.county.selectedvalue
etc
My problem is the stored procedure I sort of have the following but I can't get it to run
<code>
ALTER PROCEDURE dbo.TEST_ADVANCED_SEARCH
(@countyID int ,
@MaxAge
varchar(100),
@MinAge
varchar(100),

@smoker tinyint),
@keyword
varchar(250))

AS

DECLARE @SQL Varchar
(4000)

SELECT  @SQL =   'dbo.user_accounts.profileComplete,
dbo.user_accounts.countyID, dbo.user_profiles.smoker,
dbo.user_profiles.Age
FROM         dbo.user_accounts INNER
JOIN
                     
dbo.user_profiles ON dbo.user_accounts.userID =
dbo.user_profiles.userID
WHERE     (dbo.user_accounts.profileComplete =
1)'

IF @countyID > 0
SELECT @SQL = @SQL + ' AND
(dbo.user_accounts.countyID = @countyID)'

IF @MaxAge IS NOT
NULL
SELECT @SQL = @SQL + ' AND (dbo.user_profiles.Age <= @MaxAge)
'

IF @MinAge IS NOT
NULL
SELECT @SQL = @SQL + ' AND (dbo.user_profiles.Age >= @MinAge)
'


IF @smoker > 0
SELECT @SQL = @SQL + ' AND
(dbo.user_profiles.smoker = 1)'

IF @keyword IS NOT
NULL
SELECT @SQL = @SQL + ' AND (dbo.user_profiles.Description LIKE @MinAge)
'


EXEC(@SQL)
</code>
If I can get this to work I can add the remaining fields that I need

Am I Missing something glaringly obvious?
Any help or advice gratefully received

Thanks

View 3 Replies View Related

Help With Dynamic Where Clause In Stored Procedure

Aug 20, 2007

I have a stored procedure being called based on user search criteria. Some, the colour and vendor fields are optional in the search so i do not want that portion of the procedure to run.

at this point i keep getting errors in the section bolded below
it never seems to recognize anything after the if @myColours <> 'SelectAll'

CREATE Procedure PG_getAdvWheelSearchResults3
(
@SearchDiameter NVarchar( 20 ),
@SearchWidth NVarchar( 20 ),
@minOffset int ,
@maxOffset int ,
@boltpattern1 NVarchar( 20 ),
@VendorName NVarchar( 40 ),
@myColours NVarchar( 40 )
)
As
BEGIN TRANSACTION
SELECT *, dbo.VENDORS.*, dbo.WHEEL_IMAGES.Wheel_Thumbnail AS Wheel_Thumbnail, dbo.WHEEL_IMAGES.Wheel_Image AS Wheel_Image,
dbo.WHEELS.*, dbo.VENDOR_IMAGES.Vendor_Thumbnail AS Expr1, dbo.VENDOR_IMAGES.Vendor_AltTags AS Expr2
FROM WHEEL_CHARACTERISTICS INNER JOIN
dbo.VENDORS ON WHEEL_CHARACTERISTICS.Vendor_ID = dbo.VENDORS.Vendor_ID INNER JOIN
dbo.WHEEL_IMAGES ON WHEEL_CHARACTERISTICS.Wheel_ID = dbo.WHEEL_IMAGES.Wheel_ID INNER JOIN
FILTER_CLIENT_WHEELS5 ON WHEEL_CHARACTERISTICS.Wheel_ID = FILTER_CLIENT_WHEELS5.Wheel_ID INNER JOIN
dbo.WHEELS ON WHEEL_CHARACTERISTICS.Wheel_ID = dbo.WHEELS.Wheel_ID INNER JOIN
CLIENT_WHEEL_PRICES5 ON FILTER_CLIENT_WHEELS5.Client_ID = CLIENT_WHEEL_PRICES5.ClientId AND
WHEEL_CHARACTERISTICS.Wheel_Char_ID = CLIENT_WHEEL_PRICES5.Wheel_Char_ID INNER JOIN
dbo.VENDOR_IMAGES ON dbo.VENDORS.Vendor_ID = dbo.VENDOR_IMAGES.Vendor_ID
WHERE (dbo.VENDORS.Vendor_Active = 'y') AND (FILTER_CLIENT_WHEELS5.FCW_Active = 'y')
AND (FILTER_CLIENT_WHEELS5.Client_ID = '1039')
AND (WHEEL_CHARACTERISTICS.Wheel_Diameter =@SearchDiameter)
AND (WHEEL_CHARACTERISTICS.Wheel_Width =@Searchwidth)
AND (WHEEL_CHARACTERISTICS.Wheel_Bolt_Pattern_1 = @boltpattern1)

if @myColours <> 'SelectAll'
and WHEEL_CHARACTERISTICS.Wheel_Search_Colour = @myColours
end if


AND (cast(WHEEL_CHARACTERISTICS.wheel_Offset as int(4)) BETWEEN @minOffset AND @maxOffset)

ORDER BY CLIENT_WHEEL_PRICES5.Price asc
COMMIT TRANSACTION
GO

Anyone know how i should word the if...statements?
I have not found anything that works yet.
Thanks

View 2 Replies View Related

Dynamic Use Of Stored Procedure Resultset

Oct 12, 2006

Hello,

I have a stored procedur like this:

--------------------------------------------
ALTER PROCEDURE dbo.pdpd_DynamicCall
@SQLString varchar(4096) = null
AS

create TABLE #T1
( column_1 varchar(10) ,
column_2 varchar(100) )

insert into #T1
execute ('execute ' + @SQLString )

select * from #T1
--------------------------------------------

The problem is that I want to call different procedures that can give back different columns.
Therefor I would have to define the table #T1 generically.But I don't know how.
Can anyone help me on this problem?

thank you
Werner

View 4 Replies View Related

Dynamic Order BY In Stored Procedure

Sep 28, 2012

I can't figure out why this won't work. I want to use a variable for the 'ORDER BY' in my Stored Procedure.

I use this to order my results by product price or alphabetically from a dropdown menu. I have tried the following, but get the error below.

Code:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[SPResults]

[Code] ....

Code:
Msg 1008, Level 16, State 1, Procedure SPResults, Line 21

The SELECT item identified by the ORDER BY number 1 contains a variable as part of the expression identifying a column position. Variables are only allowed when ordering by an expression referencing a column name. Is this possible to do?

View 3 Replies View Related

Dynamic SQL Statements In A Stored Procedure

Mar 18, 2004

Hi

I have a small problem writing a stored procedure in a SQL Server 2000 database.

I would like to generate som part of the SQL inside this stored procedure that is used in an IN expression of my WHERE clause. There is no problem for me to generate a string containing my expression, the problem is that SQL-Server donīt generate a resulting SQL-statement.

Example:

CREATE PROCEDURE spDynStatement
AS

DECLARE @sPartOfSQLStatement NVARCHAR(100)

-- Some T-SQL that generates the dynamic part of the SQL-statement
-- .
-- .
-- .

-- As substitute I insert the string expression
SET @sPartOfSQLStatement = '''1''' + ', ' + '''1.5'''

-- SELECT @sPartOfSQLStatement results in: '1' , '1.5'

SELECT * FROM BBNOrganization WHERE OrgStructureID IN( @sPartOfSQLStatement ) -- does not work

SELECT * FROM BBNOrganization WHERE OrgStructureID IN( '1', '1.5' ) -- works!!!
GO

Thankfull for ideas on how to solve my problem,

Peter

View 1 Replies View Related

Dynamic ORDER BY In Stored Procedure

Apr 28, 2008

Hello,

I have this stored procedure:
SELECT * from purchase
ORDER BY
CASE @OrderBy
WHEN 'traveller_name' THEN cast(traveller_name as nvarchar(100))
WHEN 'canceled' THEN cast(canceled as bit)
END

the @OrderBy is a nvarchar(100) parameter
traveller_name is an nvarchar(100) field
canceled is a bit field


When I execute the stored procedure it works fine until I execute it sorting by canceled field. After that, I cannot sort it again using the traveller_name field. I get this eror:
Conversion failed when converting the nvarchar value 'Jason' to data type bit.
(Jason is a record in the traveller_name)
Removing the castings and sorting by just the column name does not help.

Any ideas?
Thank you

View 7 Replies View Related

Why Is This Stored Procedure Slower Than Dynamic SQL?

Oct 24, 2007



We have a procedure that does some complicated table joins to populate a temporary table (declared in the proc) and then extraneous rows are removed from the table and the remaining rows are returned.

On the production server the procedure takes 22 seconds, but the identical query in a dynamic session window of SQL Server Management Studio takes 2 seconds. That doesn't make any sense.

We've profiled the procedure and discovered that the small loop at the end of the query runs through twice with each iteration taking 10 seconds. Again - the same section (but dynamic) profiles in at 0 seconds. We further narrowed it down to the compound delete statement from the @tblResults table.

Here's the looped section of code:


-- now delete the entries with no content

declare @deleted int

set @deleted = 1

declare @tmp table ([Id] int)

while @deleted <> 0

begin


delete from @tmp

-- get all entries with no child nodes

insert into @tmp ([Id])


select distinct r.[id] from @tblResults r

where r.[id] not in

(

select [Id] from @tblResults

where [Id] in (select distinct ParentId from @tblResults)

)


-- delete entries with no documents and region match
-- (this is where the slowdown occurs)

delete from @tblResults

where [id] in

(


select t.[id] from @tmp t where t.[id] not in


(select distinct dm.metatagid from documentmetatag dm

where dm.documentid in


(select distinct dr.documentid from documentregion dr, @region r

where (dr.regionid = r.regionId or @regionIds is null)

)

)

)


select @deleted = @@rowcount

end




We then return all rows from the @tblResults table.

We are totally stumped on why the procedure would take so much longer than running the same query in a SQL Manager window. Is there some issue with temporary tables as variables in a procedure? Any ideas anyone?

Thanks,
John

View 5 Replies View Related

Dynamic Delete Stored Procedure Question

Jun 1, 2007

I have the following sp:@TABLE_NAME varchar(255),
@CONTROL_ID int
 
AS
DECLARE @sql varchar(4000)
SELECT @sql = 'DELETE FROM [' + @TABLE_NAME + '] WHERE CONTROL_ID = 5'SELECT @sql = 'DELETE FROM [' + @TABLE_NAME + '] WHERE CONTROL_ID = ' + @CONTROL_ID + ''
EXEC (@sql)
When I use the  the first SELECT line, it works great.When I use the second dynamic select, SQL raises an error:
Syntax error converting the varchar value 'DELETE FROM [TABLE_SETTINGS] WHERE CONTROL_ID = ' to a column of data type int.What is wrong?

View 2 Replies View Related

Dynamic Sql Where And Order By Clauses In Stored Procedure

Feb 17, 2008

Hi, I hope some one can help me. I have a stored procedure (Microsoft SQL 2005 Express Edition) that I want users to be able to dynamically set the, group by, order by (@orderby) and where clause (@where). I have managed to get the group by to work but can't seem to get the where and order by to work. Here's my stored procedure. Any idea how this can be done? ALTER PROCEDURE [dbo].[sp_aggregate]     -- Add the parameters for the stored procedure here @finfileid int,     @phaseid int, @supplierid int, @measurementid int, @roleid int, @groupby int, @orderby int, @where int AS BEGIN     -- SET NOCOUNT ON added to prevent extra result sets from     -- interfering with SELECT statements.     SET NOCOUNT ON;     -- Insert statements for procedure here     SELECT     MAX(ProjectFinFileMonthItems.ProjFinFileMonthItemsMonthId) AS ProjFinFileMonthItemsMonthId,                       SUM(ProjectFinFileMonthItems.ProjFinFileMonthItemsValue * ProjectFinFileMonthItems.ProjFinFileMonthItemsRate * ProjectFinFileMonthItems.ProjFinFileMonthItemsAvail                        / 100) AS total, MAX(ProjectFinFileItems.ProjPhaseId) AS phaseid, MAX(ProjectFinFileMonthItems.ProjDeliveId) AS deliveid, MAX(ProjectFinFileMonthItems.SupplierId)                       AS supplierid, MAX(ProjectFinFileMonthItems.ProjFinFileItemsId) AS ProjFinFileItemsId, MAX(ProjectFinFileMonthItems.ProjFinFileMonthItemsId)                       AS ProjFinFileMonthItemsId, MAX(ProjectFinFileMonthItems.ProjDeliveId) AS ProjDeliveId, MAX(ProjectPhases.ProjectPhaseName) AS ProjectPhaseName,                       MAX(Suppliers.SupplierName) AS SupplierName, MAX(ProjectFinFileMonthItems.RoleId) AS RoleId, MAX(Measurements.MeasurementName) AS MeasurementName,                       MAX(ProjectFinFileMonthItems.MeasurementId) AS MeasurementId, MAX(ProjectFinFileMonthItems.FinDataTypeId) AS FinDataTypeId,                       MAX(FinDataTypes.FinDataTypeName) AS FinDataTypeName, max(ProjectFinFileItems.FinFileId) as finfileid FROM         ProjectFinFileItems INNER JOIN                       ProjectFinFileMonthItems ON ProjectFinFileItems.ProjFinFileItemsId = ProjectFinFileMonthItems.ProjFinFileItemsId LEFT OUTER JOIN                       FinDataTypes ON ProjectFinFileMonthItems.FinDataTypeId = FinDataTypes.FinDataTypeId LEFT OUTER JOIN                       Measurements ON ProjectFinFileMonthItems.MeasurementId = Measurements.MeasurementId LEFT OUTER JOIN                       Roles ON ProjectFinFileMonthItems.RoleId = Roles.RoleId LEFT OUTER JOIN                       ProjectPhases ON ProjectFinFileItems.ProjPhaseId = ProjectPhases.ProjectPhaseId LEFT OUTER JOIN                       Suppliers ON ProjectFinFileMonthItems.SupplierId = Suppliers.SupplierId /*dynamic where clause needs to go here */ /*dynamic group by clause */ GROUP BY CASE when @groupby=1 then ProjectFinFileItems.projphaseid  --phaseid when @groupby=2 then ProjectFinFileMonthItems.supplierid -- supplierid when @groupby=3 then ProjectFinFileMonthItems.measurementid -- measurment when @groupby=4 then ProjectFinFileMonthItems.roleid --role else ProjectFinFileMonthItems.ProjFinFileMonthItemsId END /*dynamic order clause needs to go here */ END cheers Mark :)

View 2 Replies View Related







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