SPROC: 'LIKE' Clause And Parameter

Sep 15, 2005

Hi,

I've tried that but it does not work:

SELECT Field FROM Table WHERE Field LIKE @parameter



thanks

View 4 Replies


ADVERTISEMENT

Change Sproc Where Clause Based On Parameter Null

Apr 7, 2008

I have an optional param passed to my sproc @Pid if that is populated i want to have it part of where clause, if it is null then not in where

I know this is wrong, and very new to sqlsrver:

WHERE (Pos = 'T') AND (ofDate= @OfDate)
IF not @PID is null
AND (PID = @PID )
GROUP BY
bla bla bla


Thanks

View 12 Replies View Related

Showing Null Values From ON Inner Join Sproc CLAUSE

Jul 19, 2006

Hi all
My query has some inner joins to some tables. And problem is when any ON clause get null as value, the correspondent record is not displayed.
SELECTTableA.A, TableB.AFROM TableAINNER JOIN TableB ON TableA.A = TableB.A
What I did try:
SELECTTableA.A, TableB.AFROM TableAINNER JOIN TableB ON TableA.A = TableB.A OR TableA.A IS NULL
(but It generates redundant values from TableB)
I need to show all values even that value from Tablea is null
Thank a lot for any help

View 1 Replies View Related

SProc Expects Parameter...Help

Aug 24, 2006

This code works EXACTLY as it should on a development server that has a Framework 1.1 hotfix (operating in the 'localhost' webserver environment) but not on a production server (in a live www. web app) that does NOT have the 1.1 hotfix. Is there a code problem (if so, why should it work in the localhost) or is the hotfix on the development server needed on the production server.
(in a button sub that does an update)...Dim currentUser As New AccBusiness.User( _                                      CType(Context.User, SitePrincipal))                Dim DDName As String = currentUser.DDName                Dim NosData As String                Dim AccountDetails As New SecureNums(txtDDPhone.Text, txtDDAddress.Text)                NosData = AccountDetails.EncryptedData()                AccountDetails.UpdateAcctDetails()----------------------(business object for the update)... Public Function UpdateAcctDetails() As Boolean            Dim DataUserAcctNo As New Data.SecureCard(myModuleSettings.ConnectionString)            Return DataUserAcctNo.UpdateAcctDetails( _                myDDName, _                myNosData)        End Function--------------------------------(data object)...Public Function UpdateAcctDetails(ByVal DDName As String, _                                            ByVal NosData As String) As Boolean            Dim rowsAffected As Integer            Dim parameters As SqlParameter() = { _                New SqlParameter("@DDName", SqlDbType.VarChar, 50), _                New SqlParameter("@NosData", SqlDbType.VarChar, 512)}            parameters(0).Value = DDName            parameters(1).Value = NosData            RunProcedure("sp_Accounts_UpdateAccount", parameters, rowsAffected)            Return CBool(rowsAffected = 1)        End Function------------------------------and the sproc:ALTER PROCEDURE sp_Accounts_UpdateAccount@DDNameVarChar(50),@NosDataVarChar(512)AsUPDATE Accounts_UsersSet NosData = @NosDataWHERE DDName = @DDName------------------------------------------------------------
It all works on the development server but on the production server it gives me an error :SProc sp_Accounts_UpdateAccount expects parameter "@DDName" which was not supplied.
Can anyone suggest why this works in one environment and not the other?
Thx for looking/Reid C. 

View 2 Replies View Related

Help With Sproc And Multi Parameter

Dec 11, 2006

I'm trying to build a sproc that will return rows even if some of the parameters are blank. For example; if a user does not enter a priority, a status, or a caller the sproce should still return rows based on the other parameters.
 Can anyone help me find a way to modify my sproc bellow to allow this? I think the way I have it  bellow will only return those rows where the user has entered a parameter or the record has a null in the field.ALTER PROCEDURE dbo.ContactManagementAction

(
@ClientID int,
@Priority int,
@TStart datetime,
@TEnd datetime,
@Status nvarchar,
@ConTypeID int,
@Caller nvarchar,
@Keyword nvarchar
)

AS
SELECT Task_ID, ClientID, Priority, ActionDate, Subject, Note, Status, CompletionDate, TaskDocument, ReminderDate, Reminder, ReminderTime, Sol_ID,
DateEntered, EnteredBy, Caller, ContactTypeID, DueDate
FROM tblTasks
WHERE (ClientID = @ClientID) AND (Priority = @Priority) OR (Priority IS NULL) AND (ActionDate BETWEEN @TStart AND @TEnd) AND (Status = @Status) OR (Status IS NULL) AND
(ContactTypeID = @ConTypeID) OR (ContactTypeID IS NULL) AND (Caller = @Caller) OR (Caller IS NULL) AND (Subject LIKE @Keyword) OR (Subject IS NULL)

RETURN 

View 15 Replies View Related

SPROC With Optional Parameter

Jan 16, 2004

I need to use a parameter in a stored procedure that is optional and if it is optional I need all records returned, even if there is an entry in the field that the parameter is appllied to. Is this possible? I know I can assign a default value. but the value in the field could be one of many choices. I want to be able to specify a choice and have only those records returned or leave it blank and return all records.

Thanks for any help,

View 4 Replies View Related

Parameter Value Not Being Passed For My SProc

Mar 19, 2007

I am quite new to SSRS and am having some difficulties in trying to develop a new report via Business Intelligence Studio based on a stored procedure which requires the input of 1 parameter, and also has an optional parameter which I default to NULL in the sproc.

When I create my dataset I select the given sproc I want and when I attempt to execute it, I am prompted for the parameters the sproc expects.

However, when I enter a value in the dialog for the required Parameter I get a SQL error indicating that the parameter the sproc expects was not supplied. I have profiled the call and see the attempt to execute the sproc, but no parameter value.

Can some one tell me why the value I enter is not being passed to the sproc in my database ? Is there some special syntax that I need to use ?

I have scanned a number of sites & through the books I have and can't find anything on this. From what I have read, when I exec my sproc the parameters get recongnized & I can just enter my values. This doesn't seem to be the case.

Any help and/or suggestions are appreciated !!!
Thanks.

View 8 Replies View Related

Declaring A Tablename In A Sproc As A Parameter

Oct 2, 2006

HiCan someone please shed some light as to how this can be done. With the below sql statement as you can see I don't want to declare the table name but would rather the table name be passed in via a parameter. I've tried declaring it as a varchar parameter but it doesnt seem to like it if I don't add a valid table name. Any ideas how this can be done. Thanks.select * from @tableName where condition = condition

View 5 Replies View Related

SQL Server SPROC Cutting Off Varchar Parameter

Feb 5, 2004

Hello,

I am having trouble with a SPROC and I was wondering if anyone has had similar problems. I have a web form where users enter in a large amount of text, the web app saves that data via a SPROC into a varchar(8000) field in a SQL table. However, any amount of text beyond 255 gets cut off. I have double checked and tested my code and I dont seem to find the problem. Below is the beginning of my SPROC and as you can see, I have the correct data type and length. I have also verified the data type and length on the table and it is set at varchar(8000). Any ideas?

SPROC CODE
-----------------------------------------------
CREATE PROCEDURE Add_ProductsReview
(
@Pros varchar(100) = null,
@Cons varchar(100) = null,
@Title varchar(100),
@Body varchar(8000) -- This is the parameter with problems
)
AS......

Thanks!

View 5 Replies View Related

Sproc Create View And Parameter Problem

Aug 21, 2006

In the below sproc I want to create a view based on the incoming parameter, which is a date passed on from VB in the format 01-01-2006.

Yet getting that to work, seems quite a challenge.

I've been dabbling a bit with the sproc and QA, passing the date parameter to it in varous forms, using both single, double and triple quotationmarks and changing the parameter type to datetime.

I either wind up with a syntax error " Incorrect syntax near '01' " or " Unclosed quotation mark before the character string ".

Anyone have a guess at how to fix this issue?

Cheers, Trinsan


REATE PROCEDURE KONTROL_DRdobbeltrapportering

@rapdato as varchar

AS

if exists (select * from dbo.sysobjects where id = object_id(N'[KONTROL_vw_DRdobbeltrappbasis]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [KONTROL_vw_DRdobbeltrappbasis]

EXEC('
CREATE VIEW KONTROL_vw_DRdobbeltrappbasis
AS
SELECT Gramex_DW.dbo.Programhoved.[Rettet af DR],
Gramex_DW.dbo.Programlinie.Stationskode,
Gramex_DW.dbo.Programlinie.Udsendelsesdato,
Gramex_DW.dbo.Programlinie.[Udsendelses starttid],
Gramex_DW.dbo.Programlinie.Rapporteringsdato, Gramex_DW.dbo.Programlinie.Mediekode,
Gramex_DW.dbo.Programlinie.MUSANummer, Replace(Left(convert(varchar, [Gramex-ID]),11),''.'','''') AS GramexID,
Gramex_DW.dbo.Programlinie.Side, Gramex_DW.dbo.Programlinie.Tracknummer,
Gramex_DW.dbo.Programlinie.ISRC, Gramex_DW.dbo.Programlinie.Producentlandekode,
Gramex_DW.dbo.Programlinie.Spilletid, Gramex_DW.dbo.Programlinie.Minuttakst,
Gramex_DW.dbo.Programlinie.[Afregnet Station],
Gramex_DW.dbo.Programlinie.[Afregnet den],
Gramex_DW.dbo.Programlinie.[Afregnings ID], Gramex_DW.dbo.Programlinie.[Ur-opførelse],
Gramex_DW.dbo.Programlinie.Talestof, Gramex_DW.dbo.Programlinie.[Betalt af DR],
Gramex_DW.dbo.Programlinie.Kending, Gramex_DW.dbo.Programlinie.[Oprettelses ID],
Gramex_DW.dbo.Programlinie.[Oprettet den], Gramex_DW.dbo.Programlinie.[Oprettet af],
Gramex_DW.dbo.Programlinie.[Ændret den], Gramex_DW.dbo.Programlinie.[Ændret af],
Gramex_DW.dbo.Programlinie.[Eventuel delskæring], Gramex_DW.dbo.Programlinie.Plademærkenavn,
Gramex_DW.dbo.Programlinie.Katalogbetegnelse, Gramex_DW.dbo.Programlinie.Tracktitel,
Gramex_DW.dbo.Programlinie.Selskabsnummer, Gramex_DW.dbo.Programlinie.Indspilningsår,
Gramex_DW.dbo.Programlinie.Fonogramtitel, Gramex_DW.dbo.Programlinie.Plademærkenummer,
Gramex_DW.dbo.Programlinie.[Antal opførelser], Gramex_DW.dbo.Programlinie.[Rec nummer],
Gramex_DW.dbo.Programlinie.Indslagsnummer, Gramex_DW.dbo.Programlinie.[Afspillet gange],
Gramex_DW.dbo.Programlinie.[Afspillet minutter], Gramex_DW.dbo.Programlinie.Spilletidsløbenummer,
Gramex_DW.dbo.Programlinie.Pointtildelt, Gramex_DW.dbo.Programlinie.[Rettet af Gramex],
Gramex_DW.dbo.Programlinie.[Pgmkorlinie løbenummer], Gramex_DW.dbo.Programlinie.[Tape Kilde],
Gramex_DW.dbo.Programlinie.[Hoved artist], Gramex_DW.dbo.Programhoved.Produktionsnummer
FROM Gramex_DW.dbo.Programlinie
INNER JOIN Gramex_DW.dbo.Programhoved
ON (Gramex_DW.dbo.Programlinie.Stationskode = Gramex_DW.dbo.Programhoved.Stationskode)
AND (Gramex_DW.dbo.Programlinie.Udsendelsesdato = Gramex_DW.dbo.Programhoved.Udsendelsesdato)
AND (Gramex_DW.dbo.Programlinie.[Udsendelses starttid] = Gramex_DW.dbo.Programhoved.[Udesendelses starttid])
WHERE Gramex_DW.dbo.Programlinie.Rapporteringsdato >= ' + @rapdato + '
AND (Gramex_DW.dbo.Programlinie.Mediekode <> 1) AND
(Gramex_DW.dbo.Programlinie.Spilletid >= ''00:01:00'') AND (Gramex_DW.dbo.Programlinie.Stationskode <> ''TV2'') AND
(Gramex_DW.dbo.Programlinie.Stationskode <> ''TV2 ZULU'') AND (Gramex_DW.dbo.Programlinie.Stationskode <> ''TV2 CHARLIE''')
GO

View 2 Replies View Related

Sproc Is Returning Output Parameter Inconsistently

Mar 6, 2015

We have a service written in c# that is processing packages of xml that contain up to 100 elements of goods consignment data.

In amongst that element is an identifier for each consignment. This is nvarchar(22) in our table. I have not observed any IDs that are different in length in the XML element.

The service picks up these packages from MSMQ, extracts the data using XPATH and passes the ID into the SPROC in question. This searches for the ID in one of our tables and returns a bool to the service indicating whether it was found or not. If found then we add a new row to another table. If not found then it ignores and continues processing.

The service seems to be dealing with a top end of around 10 messages a minute... so a max of about 1000 calls to the SPROC per minute. Multi-threading has been used to process these packages but as I am assured, sprocs are threadsafe.It is completing the calls without issue but intermittently it will return FALSE. For these IDs I am observing that they exist on the table mostly (there are the odd exceptions where they are legitimately missing).e.g Yesterday I was watching the logs and on seeing a message saying that an ID had not been found I checked the database and could see that the ID had been entered a day earlier according to an Entered Timestamp.

USE [xxxxxxxxxx]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

[code]....

So on occasions (about 0.33% of the time) it is failing to get a bit 1 setting in @bFound after the SELECT TOP(1).

change @pIdentifier nvarchar(25) to nvarchar(22)
Trim any potential blanks from either side of both parts of the identifier comparison
Change the SELECT TOP(1) to an EXISTS

The only other thought is the two way parameter direction in the C# for the result OUTPUT. I have been unable to replicate this using a test app and our test databases. Have observed selects failing to find even though the data is there, like this before?

View 1 Replies View Related

Different Results With Sproc As Opposed To Simple SELECT (parameter Values)

Aug 9, 2006

Could someone please tell me why the following SELECT statement...

SELECT ID, SpecimenNr, ScientificName, Locality, TaxonFROM petrander.QueryViewWHERE (InstitutionCode = 1) AND (Collectioncode = 1) AND (ScientificName LIKE N'%le%') AND (Locality LIKE N'%Fakse%') AND (22 IN (ParentID1, ParentID2, ParentID3, ParentID4, ParentID5, ParentID6, ParentID7, ParentID8))

...gives me 9 rows back, but embedding the exact same statement in the following sproc...
set ANSI_NULLS ONset QUOTED_IDENTIFIER ONGOALTER PROCEDURE [petrander].[DynamicQuery] @taxparent int = NULL, @museum int = NULL, @collection int = NULL, @binomen Nvarchar(254) = NULL, @locality Nvarchar(254) = NULLAS SELECT ID, SpecimenNr, ScientificName, Locality, Taxon FROM QueryView WHERE InstitutionCode = COALESCE(@museum, InstitutionCode) AND CollectionCode = COALESCE(@collection, CollectionCode) AND ScientificName LIKE 'N%' + @binomen + '%' AND Locality LIKE 'N%' + @locality + '%' AND (@taxparent IN (ParentID1, ParentID2, ParentID3, ParentID4, ParentID5, ParentID6, ParentID7, ParentID8))

...and passing the exact same parameter values to with the following execute statement...

USE [Geomusdb]
GO

DECLARE @return_value int

EXEC @return_value = [petrander].[DynamicQuery]
@museum = 1,
@collection = 1,
@binomen = N'le',
@locality = N'Fakse'

SELECT 'Return Value' = @return_value

GO

gives me 0 rows!? What is different!?

Any help is greatly appreciated...

View 4 Replies View Related

How To Use A SP Parameter In A 'where In' Clause?

Oct 20, 2006

I am trying to do a  'WHERE IN' clause by taking the value of a paremeter and using it as the value in the WHERE IN clause such as: DECLARE @parm NVARCHAR(1000) = 'IBM, MOT, MSFT'SELECT * FROM SomeStockTable WHERE TickerSymbol IN (@parm)I would like to avoid using an EXEC statement and string-building this whole query, since that is ugle and hard to maintain.ANy ideas? TYVM  

View 1 Replies View Related

Where Clause As A Parameter

Aug 22, 2007

I have posted this question in the MSDN SSRS forum, but have had no luck. I'm hoping someone can give me a definite yes or no if this is possible...

I want to be able to define a parameter for a report that will represent the entire where clause.

E.g. the report's dataset will be:
SELECT name, phone FROM person WHERE @whereclause

Has anyone accomplished this?

View 4 Replies View Related

Using 'IN' Clause As Parameter

Apr 13, 2008

I have the following query:






Code Snippet

create PROCEDURE [dbo].[usp_GetSearchedEvents]

(
@SpecialityID varchar(400),
@MinistryID varchar(400)
)


AS

SELECT Distinct Events2.EventName
FROM Events2
Where ((Events2.specialityID in (@SpecialityID)) or (Events2.MinistryID in (@MinistryID)))

Now if I fill in the the variables manually, i.e, in ('1','2') it returns data. But if I execute it and enter the values of the variables as so: '1',2' it doesnt return any results. How do I accomplish this? Thanks for any input.

View 14 Replies View Related

Is There Any Way To Use A Single Parameter For An IN Clause?

Jan 18, 2008

I have an application that needs user parameters for some reports, and it allows them to enter any amount of said parameter, so the query is built like this:"Select ... Where ParameterColumn IN (" + txtParameters.Text + ")";the parameters textbox only allows numbers and commas to be on the safe side of SQL injection. now, due to this the query has to be built dynamically in the code behind  page. is there any way to use a single parameter to add all of those values? and set the parameter to the text in the control during design mode to the datasource control?something like: Select ... Where ParameterColumn IN (@Parameters) <asp:ControlParameter ControlID="txtParameters" Name="Parameters" PropertyName="Text " />whenever I try that I get something along the lines of "Error converting nvarchar '1,2,3'  to datatype int"Thanks! 

View 3 Replies View Related

Can IN Clause Accept A Parameter Value?

Jun 19, 2000

I'm trying to write an SP which takes a string parameter like '1,3,6,9' and then uses it in an IN clause of a SELECT statement to return a recordset, along the lines of:

SELECT
custname
FROM
mytable
WHERE theid IN @myparameter

...any ideas how to get this kind of thing to work. In the example, theid is a numeric value. What it needs to do, I guess, is do a string replacement of the parameter value, but the SP naturally enough attempts to compare the numeric theid value with the string @myparameter value and fails. It works OK if there's only one value in the string, because the server auto-converts the paremeter into a numeric, but if there are 2 or more values in the string then the server obviously can't do the conversion. How can I make this work?

View 1 Replies View Related

Pass IN Clause Of Where As Parameter

Sep 29, 2005

HI

I want to Run a Dynamic SQL in which i need to pass IN parameters.

DECLARE @QUERY varchar(100)
DECLARE @Paremeter varchar(10)
SET @Parameter = '1,2'
SET @QUERY='SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN (' + @parameter + ')'

But this causes an error that cant convert varchar string to int. Please dont suggest to avoid Dynamic Sql. I have to use it.

View 1 Replies View Related

Where Clause Parameter In Views

Jul 19, 2009

I have an Epicor ERP system that enables writing 'queries' in its internal format, that can see Views in the MSSQL database. Very useful, as I can write view definitions with much more flexibility than the ERP tools. As far as I can tell the ERP DB interface can't call SQL procedures.

What I want to to is to pass a value from the ERP engine that the View can use to restrict record selection. The View query produces a field that describes how far down into a nested parts list structure it has got, so the data is not in the database, it is calculated by the query.

A user may wish to restrict the depth of descent to, say 3 levels. I can filter the results set returned by the view in today's solution to only show levels up to 3, but the View still processes all levels (some 12 million records possible return) before the filtering can be applied. SLOW...

So I want to pass a parameter (if that is the right jargon) into the View to limit how much work it will do.

View 2 Replies View Related

Where Clause - Column Name As Parameter

Sep 20, 2014

In a SPROC I am creating, is there a way to use a columnName as a parameter and then do a filter on that based on a second parameter such as @columnValue ?

So instead of having to construct the WHERE clause or doing a bunch of IF statements to see what the column name is from the parameter and doing a query based upon that, is there a way to tell it to do a WHERE clause where @columnName = @columnValue ?

I do not want to use dynamic SQL string concatenation...

View 5 Replies View Related

Report Parameter As A Where Clause

Aug 21, 2007

Hello

Is it possible to construct a dataset where the parameter of the report is the where clause?

I have tried setting the dataset of the report to be a variable to execute, but any time I introduce the parameter into the dataset, the report will not run.

View 12 Replies View Related

Can A Value Be Assigned To An Output Parameter And Be Used In A Where Clause?

Dec 18, 2006

I need to update a table using a stored procedure that "UPSERTS". In this case, @OfficeId is passed with ParameterDirection.OutputSo when I update I assign the value to OfficeId like this (the office id value is being correctly assigned): SqlParameter OfficeIdParam = new SqlParameter("@OfficeId", SqlDbType.Int, 4);            if (_officeId > 0) { OfficeIdParam.Value = _officeId; }            OfficeIdParam.Direction = ParameterDirection.Output;   The following segment of the stored procedure is throwing an error that the OfficeId does not exist: Update --- @OfficeId int  output if not exists (select 1 from ORG_Office where OfficeId=@OfficeId)    begin        RAISERROR ('OfficeId does not exist in ORG_Office: E002', 16, 1) -- OfficeId does not exist.        return -1    end May this approach work, and if the operation turns out to be an Insert I may do this:select @error_code = @@ERROR, @OfficeId= scope_identity() Thank you,jspurlin 

View 1 Replies View Related

How To Replace A Default Value With Parameter From A Where Clause

Jul 19, 2007

Table-Account0
column   EAIndex  ã€?BillerCodeã€?ChainCodeã€?PostDateã€?PostAmountã€?BalanceDateã€?BillBegDateã€?BillEndDateã€?BillCountã€?ChAmount
 Table-Biller
 CompanyCodeã€?BilerCodeã€?BillerNameã€?UniformNoã€?BusCodeã€?AcctNoã€?BillerInfoList
Table-DataBackup
column CompanyCode�Keepmonth
 in Table-Account0  , I use this sql query to retrieve data by column PostDate-3
Select * From ZT_EAccount0  Where isNumeric(PostDate) = 1 And PostDate < Convert(varchar(10),DateAdd(Month,-3,GetDate()),112)
now , I don't won't to lock the value "-3" , the subtract value will depend on the value of colum keepmonth from table DataBackup
can you please tell me how to do ?
 
thank you very much
 

View 4 Replies View Related

Stored Procedure Parameter And IN Clause

Dec 9, 2003

This works:

WHERE ltrim(str((DATEPART(yyyy, dbo.Media_Tracking_Ad_History.ADDATE))) IN ('2003','2004','2005'))


This doesn't:

WHERE
WHERE ltrim(str((DATEPART(yyyy, dbo.Media_Tracking_Ad_History.ADDATE))) IN (@strYears))


@strYears will work if I only pass a single value such as 2003. I've tried every combination of single and double quotes I can think of to pass multiple values but nothing works. Any suggestions?

View 4 Replies View Related

How To Add A Where Clause By Parameter In A Stored Procedure

Aug 1, 2005

What i want is to add by parameter a Where clause and i can not find how to do it!CREATE PROCEDURE [ProcNavigate]( @id as int, @whereClause as char(100))ASSelect field1, field2 from table1 Where fieldId = @id    /*and @WhereClause */GOany suggestion?

View 1 Replies View Related

String Parameter With Comma To Where Clause

Mar 20, 2014

I want to bring a string parameter to where clause like this:

select .. from ...
Where Code IN (@Code)

When @Code is 'ABC' it works but when @code is 'ABC, XYZ' it won't work. I know for IN statement we should use IN ('ABC', 'XYZ') and I tried make @code = '''ABC'', ''XYZ''' still not working. I tried

Print '''ABC'', ''XYZ'''

I got 'ABC', 'XYZ' but why it does not work in @Code?

View 4 Replies View Related

Passing Orderby Clause As Parameter In SP

Jan 24, 2008

Hi,

I have a requirement where i have to pass OrderBy clause to an SP as an parameter. I dont want to use dynamic sql query so i am running into problem.

Below is my procedure..

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
Create Proc [dbo].[USP_GetData]
@sortBy varchar(100),

as

BEGIN

SELECT *
FROM
(SELECT CC.C1, CC.C2, CC.C3, CC.C4,
ROW_NUMBER() OVER(ORDER BY @sortBy) as RowNum
FROM T1 CC
) as e
END

The thing is, if i execute the procedure as
EXEC USP_Get_Data ('C1 asc'), it runs without any error but it gives me unsorted result.

I am not able to figure out why.

Any help in this will be appriciated.

Regards,
Salim.

View 16 Replies View Related

WHERE Clause Using Different Column Passed By Parameter

Jul 30, 2007

Hi all,

I'd think this is possible but I'm having trouble getting data returned from the query. Fields PART_NUMBER and INTERNAL_SKU exist in the SKU table. This will be inside a SP. If user passes 'PN' as first parameter then I'd need to have the WHERE clause by PART_NUMBER, if he passes 'SK' (or anything else for now) then the WHERE clause shold be by SKU.

Can't I just build the WHERE by replacing @SearchField with its value ? I've looked up the CASE statement but I don't think it does what I need.


DECLARE @strSearchType varchar(2)

DECLARE @strSearchValue varchar(15)

DECLARE @SearchField varchar(15)

set @strSearchType = 'PN'

set @strSearchValue = '1234567'


IF @strSearchType = 'PN'

begin

set @SearchField = 'PART_NUMBER'

end

ELSE

begin

set @SearchField = 'INTERNAL_SKU'

end

SELECT

SKU as 'SKU',

PART_NUMBER as 'PartNumber',

DESCRIPTION as 'Description'

FROM SKUs

WHERE @SearchField = @strSearchValue

FOR XML PATH('SKU'), ROOT('Response')


Thanks,

ST

View 4 Replies View Related

Select Stored Procedure With One Parameter And A Where Clause

Jan 13, 2007

Here is my procedure:
ALTER PROCEDURE dbo.SelectMeds
@RX int
AS
SELECT RX FROM tblMeds WHERE RX= @RX
 
RETURN
but it return no rows, how do I fix this?

View 4 Replies View Related

Stored Procedure With Variable As Only Parameter In Where Clause

Feb 1, 2008

Hello,
 I want to execute a sproc where the query statement goes something along these lines:
SELECT * FROM myTable WHERE @aVarCharVariable
@aVarCharVariable contains column names and their possible values
How do I achieve this?
Cheers!
/Eskil

View 7 Replies View Related

How To Pass Dynamic Parameter To Order BY Clause

Sep 13, 2004

Hi,

I use a DataGrid to show the data, and I want it has a sorting and Paging function,
so I use dataset to collect the data from middle tier function and stored procedure.
I have code in aspx page like BindData(ViewState("SortExpr")).

In the stored procedure I pass SortExpr as parameter as following:

CREATE Procedure Ruying_AutoSearch10
(
@Make varchar(50),
@Model varchar(50) = NULL,
@Condition varchar(20) = NULL,
@Miles float,
@Zipcode varchar(5),
@SortExpr varchar(100)
)
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 a.Model = IsNull(@Model,a.Model)
AND a.Condition = IsNull(@Condition, a.Condition)
AND dbo.DistanceAssistant(z.Latitude,z.Longitude,r.Latitude,r.Longitude) <= @Miles
ORDER BY @SortExpr
END
ELSE
SELECT -1 As ZIPCode
--ZIP Code not found...
GO


but I got the error as "variables are only allowed when ordering by an expression referenceing
a column name". How I fix this error? Please help.

Thanks.

Lin

View 9 Replies View Related

Passing A Stored Procedure Parameter Into An IN Clause

Jul 30, 2007

Hi All :)

I have a stored procedure which, initially, I had passed a single parameter into a WHERE clause (e.g ...WHERE CustomerCode = @CustCode). The parameter is passed using a DECommand object in VB6.

I now require the sp to return values for more than one customer and would like to use an IN clause (e.g ...WHERE CustomerCode IN(@CustCode). I know I could create multiple parameters (e.g. ...WHERE CustomerCode in (@CustCode1, @CustCode2,...etc), but do not want to limit the number of customers.

If I set CustCode to be KA1001, everything works fine. If I set CustCode to be KA1001, KA1002 it does not return any records.

I think the problem is in the way SQL Server concatenates the stored procedure before execution. Is what I am attempting to do possible? Is there any particular format I need to set the string parameter to? I've tried:

KA1001', 'KA1002 (in the hope SQL Server just puts single quotes either side of the string)

and

'KA1001', 'KA1002'

Both fail :(

Any ideas?

Regards

Xo

View 11 Replies View Related

Case Statement On Where Clause If Parameter =NULL

Jun 3, 2008

I am working on a Function that takes multiple parameters. I have a query that populates a temporary table, and then it processes some logic. My question is, if the parameter is passed as null, I dont want the query to be affected by this null value. Rather, I would like to not pass it at all to the query. So if the parameter is NULL, dont pass it through the query. I have the following but its not compiling right:


SELECT bom.pEngr_BOM_ID , bom.fEngr_Item_ID, det.pEngr_BOM_Detail_ID, 1, bom.Bill_Type, bom.Rev_Ltr, bom.Series_Ltr
FROM dbo.Engr_BOM_Control bom WITH (nolock)
INNER JOIN dbo.Engr_BOM_Detail det WITH (nolock)
ON det.fEngr_BOM_ID=bom.pEngr_BOM_ID
WHERE bom.pEngr_BOM_ID=@v_pEngr_BOM_ID
AND det.fEngr_BOM_ID=@v_pEngr_BOM_ID
CASE WHEN @v_Bill_Type IS NOT NULL THEN
AND bom.Bill_Type=@v_Bill_Type
END

View 3 Replies View Related







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