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?
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.
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!
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?
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.
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.
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...
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.
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
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 ?
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?
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?
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?
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.
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
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:
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.
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)
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
I am trying to merge 2 pieces( i.e procedures , or stored proc) of sql together.
My simple QueryA
SELECT colA, colB, colC, colD FROM tableA WHERE colD IS NOT NULL
My simple QueryB
SELECT colA, colB, colC, colD FROM tableA WHERE colC IS NOT NULL
I am trying to merge these 2 pieces if sql together by passing a input parameter which will decide which query to run. So if I pass an input parameter QueryA , it will run QueryA. If I pass an imput parameter QueryB, it will run QueryB.
Essentially both my queries are the same besides the where condition. Is there a way to merge it into one query (and not use if conditions and make my storedproc long) and apply the where condition depending on what input parameter is passed in ?
I know it can be done using dynamic SQL construction. But any other ways ?
Also can someone also give in the solution in PL/SQL.
Is it possible to pass a report parameter that is defined as a string to the following SQL statement that is using an "IN" clause ?
WHERE (ANALYST.User_Bemsid IN (@Report_Parameter_Bemsid))
If I pass a single value (I.E. A) it works okay, but once I try to pass multiple values (I.E. A,B or 'A','B') it returns no data.
Using Crystal reports I can pass multiple values via a report prompt into the SQL "IN" clause and seems that SQL Reporting Services should also have this feature. What do I need to do to get it working ?
I'm trying to create a WHERE clause that will have different results depending on a parameter that is entered. For example, if you put in a number, it will only calculate the rows where the column ID matches that number. However, if you put in 0, which doesn't exist in that column ID, it will instead calculate all the data in the table.
So the below would be a very basic idea of what I'm trying to do, but I'm not sure how to do it with proper syntax.
the code below works (this is only a quick dumbed down version of the actual code, it might not work 100% for all cases). Is it at all possible to exploit the functions that were added to SSQL since v. 2005 to simplify this code ?
In SSRS, a parameter allows the user to create a list of invoices (from CRM) to be ordered in any of the following ways the user prefers:
'Document Date (most recent date first)' 'Document Number (highest number first)' 'Document Date (most recent first) and Number' 'Document Number (lowest number first)'
The invoices have a (supposedly) sequential identity-generated number. However Accounting may want to set a different date than the creation date on some invoices. So there is no way the invoice numbers will be in the same sequence as the invoice dates.
So I just created the "sorting fields" - they appear as junk in the output dataset (just do not drop them in the SSRS tablix - they have to be part of the SELECT statement to be usable in the ORDER BY clause.
The code is:
DECLARE @ls_OrderBy varchar(80) --'Document Number (highest number first)' --'Customer and Document Date (most recent date first)' --'Customer and Document Number (highest number first)' --'Document Date (most recent first) and Number'
Hello--I do not know if this group can help me with SQL Server Reporting Services ... but here it goes. I have a report built on a query and I want to be able to send a parameter (@theWhere) that is a string which is a where clause "(MEGLOMART_TYP_CODE <> 'XYZ' AND MEGLOMART_STAFF_SHORTAGE > 25)" these strings can vary depending on what columns the user selects and what operators they want to use. Generation of proper SQL for the where clause has been verified, I just need to be able to pass these, is there any way to do this...see example query below and how I was planning on using the @theWhere variable...
I'm writing some generalized stored procedures for use form managed code. The following stored proc works great:
CREATE PROCEDURE fnd_Send ( @Message VARCHAR(5000), @Contract SYSNAME, @MessageType SYSNAME, @FromService SYSNAME, @ToService VARCHAR(100), @Encrypted Bit ) AS BEGIN DECLARE @Handle UNIQUEIDENTIFIER;
BEGIN DIALOG CONVERSATION @Handle FROM SERVICE @FromService TO SERVICE @ToService ON CONTRACT @Contract WITH ENCRYPTION = OFF;
SEND ON CONVERSATION @Handle MESSAGE TYPE @MessageType(@Message);
Notice the use of SYSNAME parameters €“ translating the parameter into an object name - allows it to work in the BEGIN DIALOG statement when an system object is needed. Works create and cues up generic messages.
The following will not compile:
CREATE PROCEDURE fnd_Receive ( @Queue SYSNAME, @Message VARCHAR(5000) out, @MessageType SYSNAME out ) AS BEGIN DECLARE @Handle UNIQUEIDENTIFIER;
RECEIVE TOP (1) @Handle = conversation_handle, @MessageType = message_type_name, @Message = message_body FROM @Queue; END GO
It won€™t let me use the SYSNAME field @Queue in the FROM clause. I€™m getting an unfriendly:
Msg 102, Level 15, State 1, Procedure fnd_Receive, Line 15 Incorrect syntax near '@Queue'.
It looks like maybe I can€™t bind a variable in the FROM clause €“ perhaps like you cannot in a SELECT statement. I can fall back to dynamic SQL in the stored proc or in the managed code; I was hoping not to.
Can anyone shed any light on this? Also, are there any other techniques I'm missing to avoid falling back to a dynamic SQL statement.
I am writing a stored procedure and have a query where I create a variable from other table
Declare @Sem varchar (12) Null @Decision varchar(1) Null Select emplid,name, Semester Decision1=(select * from tbldecision where reader=1) Decision2=(select * from tbldecision where reader=2) Where Semester=@Sem And Decision1=@Decision
But I am getting error for Decision1 , Decision2. How can I do that.
Result (While I am selecting 'Yes' in dropdown) ---------------------------------------------- incident_id usr_id item_id 10059926 191 61006 10054444 222 3232
SELECT incident.incident_id,incident.usr_id,incident.item_id FROM incident where exists (How i can write query here to check the act_type_sc=ADD_ATTCHMNTS is exists)
I understand that Multi-Select Parameters are converted behind the scenes to an In Clause when a report is executed. The problem that I have is that my multi-select string parameter is turned into an in claused filled with nvarchar/unicode expressions like:
Where columnName in (N'Value1', N'Value2', N'Value3'...)
This nvarchar / unicode expression takes what is already a fairly slow-performing construct and just drives it into the ground. When I capture my query with Profiler (so I can see the In Clause that is being built), I can run it in Management Studio and see the execution plan. Using N'Values' instead of just 'Value1', 'Value2','Value3' causes the query performance to drop from 40 seconds to two minutes and 40 seconds. It's horrible. How can I make it stop!!!?
Is there any way to force the query-rewriting process in Reporting Services to just use plain-old, varchar text values instead of forcing each value in the list to be converted on the fly to an Nvarchar value like this? The column from which I am pulling values for the parameter and the column that I am filtering are both just plain varchar.
I have a quite big SQL query which would be nice to be used using UNION betweern two Select and Where clauses. I noticed that if both Select clauses have Where part between UNION other is ignored. How can I prevent this?
I found a article in StackOverflow saying that if UNION has e.g. two Selects with Where conditions other one will not work. [URL] ....
I have installed SQL Server 2014 and I tried to use tricks mentioned in StackOverflow's article but couldn't succeeded.
Any example how to write two Selects with own Where clauses and those Selects are joined with UNION?