I have a stored procedure that performs a search function with params:
@username nvarchar(50)
@country nvarchar(50)
and like 10 more.
A user may provide values for these params optionally.
So when the @username var is left blank, there should be no filtering on the username field (every field should be selected regardless of the username)
Currently my statement is:
select username,country from myUsers where
username=@username and country=@country
With this statement when a user provides no value for username the username field selects on ''m which returns ofcourse nothing...
hiI need to write a stored procedure that takes input parameters,andaccording to these parameters the retrieved fields in a selectstatement are chosen.what i need to know is how to make the fields of the select statementconditional,taking in consideration that it is more than one fieldaddedfor exampleSQLStmt="select"if param1 thenSQLStmt=SQLStmt+ field1end ifif param2 thenSQLStmt=SQLStmt+ field2end if
Hi, is it possible to do a conditional WHERE in T-SQL? I have a table with a column that consists of a reference that starts with either a single alpha character or two alpha characters followed by four numeric digits (the numeric portion is always unique but the alpha isn’t). E.g. A1234, AB1235, AB1236, C1237, HT1238. What I want to do is select a range of rows based on the numeric portion of this reference column. In other words I want to select say 50 rows starting from row 1000 (rows 1000 to 1050) regardless of whether there is one or two alpha characters preceding the numerics.The Stored procedure I have so far works (using COUNT for testing) for selecting a range of rows that has two alpha's at the start. However, if I simply add an OR to the WHERE to select rows where there is a single alpha in the reference column, when a single alpha reference is found it will fail the first logical check for two alpha's giving an error condition. Therefore, how can I incorporate a conditional WHERE using IF or some alternative method, so that it will also give me all the rows in the number sequence that start with either single or double alpha's within the same SELECT / WHERE statement?
Thanks for any help.ALTER PROCEDURE [dbo].[sp_Test]
( @startRef int, @endRef int )
AS
BEGIN
SELECT Count(*) FROM myTable WHERE ((SUBSTRING(Ref,3,LEN(Ref)-2) BETWEEN @startRef AND (@startRef + @endRef)))
Hi all,I have one for all the blackbelters out there: is there a way i canmake a stored procedure where i can control the where statement withvariables? I have to do some complex transformations to get compose afact table for MSAS and there a a lot of similarities between thequeries and a few differences because of different account methodsetc. (booking in starting date, booking stuff on order entry datesetc) I want to put a combination of different rules in differentmembers of dimensions.An example of what i mean:CREATE STORED PROCEDURE dbo.FILLFACT (@PAR1, @PAR2)ASINSERT INTO FactTable (blah blah)SELECTIF @PAR1 = 'OrderDate'SourceView.OrderdateELSESourceView.StartDate,etc etc...FROMSourceViewWHEREIF @PAR2 = 'WholeTable'1=1IF @PAR2 = 'Incomplete'EndDate IS NULL OR EXIST (SELECT * FROM Exceptions WHERE...., etc)This way i could fill my fact table withEXEC dbo.FillFact 'beginDate','Wholetable'EXEC dbo.FillFact 'begindate', 'Rulebook1'EXEC dbo.FillFact 'BeginDate', 'Exceptions'etcetera.This is not an actual SQL script i use, just an example of what i'mtalking about. Or maybe i could pass the where statement entirley as avariable? But i can't use SET @PAR1 = 'EndDate IS NULL' and then useWHERE @PAR1 can I?I hope i'm making sense. Does anyone know if this is possible? Rightnow i have a procedure that is composed of a dozen of sql scripts thatare mostly the same, but i have to copy it for every combination ofsituations and then, of course, new stuff has to be added on 12different places. Again and again.Any thoughts?TIA,Gert-Jan van der Kamp
Hi, I've been looling around, but was unable to correctly use a conditional statement in a T-SQL Query. I have this SQL query and in it how I would do if it was C#. If someone could please help me get what I need I would appreciate it a lot. Here is the query:
Code Block
SELECT Ficha, Almoxarifado, [Código do Item], Descrição, Unidades.Unidade, [1ª Contagem], [2ª Contagem], Recontagem, Observações, Cancelar FROM Fichas INNER JOIN Itens ON [Código do Item] = Código INNER JOIN Unidades ON Itens.Unidade = Unidades.ID WHERE Ficha BETWEEN 01 AND 5000 AND Recontagem IS NULL AND
/* What I would do in C#, but need in T-SQL*/ if ([1ª Contagem] > [2ª Contagem]) {
if ([2ª Contagem] / [1ª Contagem] < 0.99)
return true; else {
if ([1ª Contagem] / [2ª Contagem] < 0.99)
return true; }
I really need a help in this. Does anyone know how to accomplish this? Thanks. Regars, Fábio
I'm trying to gather some user statistics based on 3 conditions. First I want to check if the referring querystring is already in the database. If not insert it into the db. Second, if the querystring is already in the database, then check if the ip-address of the user is already in the database. If it is, then check if the ip address was inserted today. If not, update the "refCountIn" field with +1. The problem lies in the third condition where we check if the ip-address was inserted today and if false, update the "refCountIn" field with +1 and if true, do nothing.Below is the code I have until now: 1 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 2 3 ' *** Declare the variables 4 Dim getStatCmd As String 5 Dim updStatCmd As String 6 7 Dim myRef As String = Request.QueryString("ref") 8 Dim myQueryString As String = Request.ServerVariables("QUERY_STRING").Replace("ref=", "") 9 Dim myRemoteAddr As String = Request.ServerVariables("REMOTE_ADDR") 10 Dim myHttpReferer As String = Request.ServerVariables("HTTP_REFERER") 11 12 Dim dtNow As Date = DateTime.Now 13 Dim dtToday As Date = DateTime.Today 14 15 ' *** Conditional INSERT command 16 getStatCmd = _ 17 "IF EXISTS(SELECT 'True' FROM tblReferers WHERE robotName = '" & myQueryString & "' AND refIpAddress = '" & myRemoteAddr & "' AND refTime = '" & dtToday & "') " & _ 18 "BEGIN " & _ 19 "SELECT 'This clickin has already been recorded!'" & _ 20 "END ELSE BEGIN " & _ 21 "SELECT 'Clickin recorded' " & _ 22 "INSERT INTO tblReferers(robotName, refIpAddress, refReferer, refTime) " & _ 23 "VALUES(" & _ 24 "'" + myQueryString + "'," & _ 25 "'" + myRemoteAddr + "'," & _ 26 "'" + myHttpReferer + "'," & _ 27 "'" + dtToday + "')" & _ 28 "END " 29 30 31 ' *** Conditional UPDATE command 32 updStatCmd = _ 33 "IF EXISTS(SELECT 'True' FROM tblReferers WHERE robotName = '" & myQueryString & "' AND refIpAddress = '" & myRemoteAddr & "' AND refTime <> '" & dtToday & "') " & _ 34 "UPDATE tblReferers " & _ 35 "SET refCountIn = refCountIn + 1, refTime = '" & dtNow & "' " & _ 36 "WHERE refIpAddress = '" & myRemoteAddr & "' AND robotName = '" & myRef & "'" 37 38 Dim insConnCmd As New SqlCommand(getStatCmd, New SqlConnection(connSD)) 39 Dim updConnCmd As New SqlCommand(updStatCmd, New SqlConnection(connSD)) 40 41 insConnCmd.Connection.Open() 42 insConnCmd.ExecuteNonQuery() 43 insConnCmd.Connection.Close() 44 45 updConnCmd.Connection.Open() 46 updConnCmd.ExecuteNonQuery() 47 updConnCmd.Connection.Close() 48 49 End Sub Anyone with an idea on how to solve this one? I think I need to write a subquery for the third condition, but I don't have a clue on how to handle this.Thanks in advance for your help!
I'm learning SQL and here I'm trying to use two things that I'm not familiar with - IF statements and the Inserted temporary table. Here's the background - skip this paragraph if you like. I'm working on a tasking system for the Help Desk - they get requests from the web site for various items and I break up the request into Software, Hardware, Accounts, etc tables and list the status of each item as "Requested". I'm also keeping a Tasks table to make work orders for each item requested. I've got triggers on the Accounts and Hardware tables that automatically make a new task for those items but the Software is more tricky because all software for a given request should be just one task. Software installs are all done by one person at the same time. So I'm trying to make a trigger that creates a new Task when a new Software record is inserted. But if a task already exists with the same RequestID (meaning they requested two peices of software and this is the second one), then I just want to update the task already created. Here's what I got: 1 CREATE TRIGGER [NewSoftwareTask] 2 ON [dbo].[Software] 3 AFTER INSERT 4 AS 5 BEGIN 6 7 -- If a software task already exists for this request 8 -- then update it. Otherwise create a new task. 9 10 if exists(select TasksID 11 from Tasks 12 where Tasks.RequestsID = inserted.RequestsID and 13 TasksType = 'Software') 14 BEGIN 15 UPDATE [BGHelpdesk].[dbo].[Tasks] 16 SET [TasksDescription] = [TasksDescription] + vbcrlf + "Install " + inserted.SoftwareType + ". " + inserted.SoftwareComments 17 WHERE Tasks.RequestsID = inserted.RequestsID and 18 TasksType = 'Software' 19 END 20 21 else 22 23 BEGIN 24 INSERT INTO [BGHelpdesk].[dbo].[Tasks] 25 ([RequestsID] 26 ,[TasksType] 27 ,[TasksSubType] 28 ,[TasksTitle] 29 ,[TasksDescription]) 30 SELECT 31 s.RequestsID 32 ,'Software' 33 ,s.SoftwareType 34 ,'New ' + s.SoftwareType + ' Account for Request ' + cast(s.RequestsID AS varchar) 35 ,s.SoftwareComments 36 FROM Software s join 37 inserted ON s.SoftwareID = inserted.SoftwareID 38 END 39 END 40 GO
It keeps balking at lines 12 and 17 saying "The multi-part identifier "inserted.RequestsID" could not be bound." The ELSE statement is what I use on the other tables and it works fine so the inserted temp record seems pretty straightforward but I must be doing something wrong...
Yet another puzzling question. I remember I saw somewhere a particular syntax to select a column based on a conditional predicate w/o using a user defined function. What I want to accomplish is this : SELECT (if column colA is empty then colB else colA) as colC from SomeTable. Possible ? Not possible? Have I hallucinated ?
currently I am creating a total if the date is between two entered dates:
select sum(case when exigo_data_sync.orders.orderdate between @prevMonthStart and @prevMonthEnd then 1 else 0 end) as PrevMonthCount,
I need to check an additional column for ($1.00) or $1.00. If it contains $1.00 then proceed as normal and add to the total. If it contains ($1.00) then subtract one from the total. Any advice?
This is probably quite simple, but it isn't sticking out at me.
In a simple table with two groups, I want to conditionally set the color of the first group to red or green based upon whether ANY value for this field equals a particular string.
I know how to conditionally set the color of the field. However, the below code appears to only compare the FIRST value in Fields!myField.Value to the string "bad". I want it to return "Red" if ANY of the values for Fields!myField.Value = "bad".
Have a View where I need to enter a conditional IF_THEN_ELSE statement in a new field (field has an alias). If this were an Access query I would do following:
IIf([dbo.AR1_CustomerMaster.EmailAddress] Is Null, "A", "B")
Hi,I'm trying to do calculations in a SQL statement, but depending on onevariable (a.type in example) I'll need to pull another variable fromseperate tables.Here is my code thus far:select a.DeptCode DeptCode,a.Type Type,(a.ExpenseUnit / (select volume from TargetData b where b.type =a.type)) ExpenseFromcalc1 aThe problem... a.Type can be FYTD, Budget, or Target... and dependingon which one it is, I need to make b either FYTDData, TargetData, orBudgetData. I'm thinking a case statement might do the trick, but Ican't find any syntax on how to use Case in an MS SQL statement. EvenIf statements will work (if that's possible), though case would beless messy.Any suggestions would be much appriciative. Thanks...Alex.
Is it possible to have a conditional union statement in a stored proc?Here's an example on the northwind database. If says there's a syntaxerror near the UNION statement. Looks like it doesn't like having theBEGIN directly in front of it.Is the only solution to create a dynamic sql string then call exec onit?Any help appreciated.Tom.CREATE PROCEDURE usp_test(@both int = 1)ASSET NOCOUNT ONSELECT * FROM territories WHERE regionid = 1IF @both = 1BEGINUNIONSELECT * FROM territories WHERE regionid = 2ENDGO
What I need to do in seperate a group of numbers into two different categories based on a phase code. I have acheived this through two conditional statements, but when I try to total the numbers that were returned for each group I receive an #error.
This is an example of the switch statement I used in order to return the correct values for the Implemenataion.
I've tried substituting a 0 in for the "" at the end of each statement. I've also tried to take the first statement and put it into its own table field named ImplementationLedger, and them summing it. ie. =SUM(Fields!ImplementationLedger.Value)
After many hours search many forums and many failed experiments, I figure it's time to turn to the experts.
I need to execute a query that changes the returned data based upon a parameter's value. In my example below, the lob field contains both text values and nulls.
SELECT uniqueID, lob, xdate FROM mytable WHERE
CASE WHEN @myparam = 'ALL'
THEN
xdate >= '2007-09-01' ELSE
xdate >= '2007-09-01' or lob = @myparm END
I've experimented with various forms of the LIKE function, checking for null/not null and keep coming up blank.
I thought about using an IF statement and creating different versions of the entire statement, however, in real-life I need to do this with four fields using four parameters (one for each field). The permutations are a little too much.
2) I am not able to get an If/Then statement to work. I am able to use the followingl; however, ideally I would want to have multiple if/else statements:
My source file is showing column 10 as string. My destination table is datetime. I am using the derived transformation with a conditional statement. How do I convert the value from string to date. Everywhere I try the (DT_DATE) I get an error.
I am trying to write a Transact-SQL statement and am having no success. I have a customers table that has some duplicate Customer Numbers in it, however the records do have a unique Reference Number. I am trying select all records that match a list of Customer Numbers but if there are more than 1 matching Customer Number I only want the one with the largest Reference Number.
My BASIC Select Statement is:
SELECT Cust_Ref_No, Customer_No, Customer_Name, Address1, Address2, Suburb, State, Postcode, Phone FROM Customers WHERE Customer_No IN (SELECT Customer_No FROM temp_Customers)
Much to my HORROR I found that what I am trying to do is simple in MS Access using the “First” Function – Such as below:
SELECT First(Cust_Ref_No) AS Cust_Ref_No, Customer_No FROM Customers GROUP BY Customer_No ORDER BY First(Cust_Ref_No), Customer_No;
There appears to be no “First” Function in Transact-SQL. Is someone able to show me how to achieve the same results in Transact-SQL as I can get with MS Access (I’d HATE to think that MS Access has more functionality in querying data than SQL Server in any way at all)?
P.S. I really need to run the select statement as one step rather than splitting it up into parts.
I have a data model with 7 tables and I'm trying to write a stored procedure for each table that allows four actions. Each stored procedure should have 4 parameters to allow a user to insert, select, update and delete a record from the table.
I want to have a stored procedure that can accept those 4 parameters so I only need to have one stored procedure per table instead of having 28 stored procedures for those 4 actions for 7 tables. I haven't found a good example online yet of conditional logic used in a stored procedure.
Is there a way to add a conditional logic IF statement to a stored procedure so if the parameter was INSERT, go run this statement, if it was UPDATE, go run this statement, etc?
Is there a way in order to execute a subscribed report based on a certain criteria?
For example, let's say send a report to users when data exist on the report else if no data is returned by the query executed by the report then it will not send the report to users.
My current situation here is that users tend to say that this should not happen, since no pertinent information is contained in the report, why would they receive email with blank data in it.
I have the following code in the color property of a textbox. However, when I run my report all of the values in this column display in green regardless of their value.
I want to know how I can create conditional FROM WHERE clauses like below ..
SELECT X,X,X FROM CASE @intAltSQL > 0 Then Blah Blah Blah END CASE @intAltSQL = 0 Then Blah END WHERE CASE @intAltSQL > 0 Then Blah Blah Blah END CASE @intAltSQL = 0 Then Blah END
Im faced with the following design issue.. on my site there are different profiles: a city profile, a restaurant profile and a user profile. in my DB:City profiles are stored in tbCities cityID int PK shortname nvarchar(50) forumID int FK (...) Restaurant profiles are stored in tbRests restID int PK shortname nvarchar(50) forumID int FK (...) User profiles are stored in tbUsers userID int PK shortname nvarchar(50) forumID int FK (...) as you can see a single ID value (for CityID,restID or userid) might occur in multiple tables (e.g. ID 12 may exist in tbRests and in tbUsers)Each of these profile owners can start a forum on their profile. forumID in each of the above tables is a FK to the PK in tbForums:forumID intforumname nvarchar(50) (...) Now imagine the following: a site visitor searches ALL forums...say he finds the following forums:ForumID Forumname1 you opinion on politics2 is there life in space?3 who should be the next president of the USA? a user may want to click on the forum name to go to the profile the forum belongs to.And then there's a problem, because I dont know in which table I should look for the forum ID...OR I would have to scan all tables (tbCities,tbRests and tbUsers) for that specific forumid,which is time-consuming and I dont want that! so if a user would click on forumID 2 (is there life in space?) I want to do a conditional inner join for the tablecontainingforumID (which may be tbCities,tbRests or tbUsers) select tablecontainingforumID.shortname FROM tablecontainingforumID tINNER JOIN tbForums f ON t.ForumID=f.ForumIDwhere f.ForumID=2 I hope my problem is clear..any suggestions are welcome (im even willing to change my DB design if that would increase effectivity)
I encounter a T-Sql problem related to if conditional processing:The following script execute an insert statement depending on whether column 'ReportTitle' exists in table ReportPreferences. However it gets executed even when ReportTitle column is not present.Could anyone offer some advice? IF(Coalesce(Col_length('ReportPreferences','ReportTitle'),0) > 0) BeginINSERT INTO dbo.DefaultsSELECT FinancialPlannerID,ReportTitleFROM dbo.ReportPreferencesendGO
I have an SqlDataSource that uses a value from the query string in the WHERE clause of the sql statement. The sql is something like this: SELECT * FROM myTable WHERE myfield = @myfield and I have the QueryStringParameter setup like this: <asp:QueryStringParameter Name="myfield" QueryStringField="myfield" /> What I need is for the sql statement to return all records in the case that "myfield" is not defined in the query string. How would I implement this? Thanks, Joshua Foulk
Hello all, my update statement works as expected, but lacks some conditional logic. How can I change the statement to not decrement qtyonhand if the quantity is 0? Additionally, I would need to return to the calling application something that would allow me to populate a label with a message to the user.. How can that be accomplished? Here is my sproc:CREATE PROCEDURE [webuser].[cssp_removeItem] @lblID int AS Update cstb_inventoryset qtyonhand = qtyonhand -1where Id = @lblIDGO Here is my app code: Try Dim cmd As SqlCommand = cn.CreateCommand cmd = New SqlCommand("cssp_removeItem", cn) cmd.CommandType = CommandType.StoredProcedure With cmd cmd.Parameters.Add("@lblId", SqlDbType.Int).Value = lblId.Text End With If Not cn.State = ConnectionState.Open Then cn.Open() End If cmd.ExecuteNonQuery() Catch ex As Exception Response.Write(ex.ToString) Finally If Not cn.State = ConnectionState.Closed Then cn.Close() cn = Nothing End If
Hi, [SQL 2005 Express] I would like a DropDownList to be populated differently depending on the selected value in a FormView. If the FormView's selected value (CompanyID) is 2, then the DropDownList should show all Advisers from the relevant Company. Otherwise, the DropDownList should show all Advisers from the relevant Company where the TypeID field is 3. Here is the SQL for case 1: SELECT AdviserID, AdviserName FROM Advisers WHERE (CompanyID = @CompanyID). Here's the SQL for case 2: SELECT AdviserID, AdviserName FROM Advisers WHERE (CompanyID = @CompanyID) AND (TypeID = 3). Here's my best (failed) attempt to get what I want: SELECT AdviserID, AdviserName FROM Advisers WHERE IF @CompanyID = 2 THEN BEGIN (CompanyID = @CompanyID) END ELSE BEGIN (CompanyID = @CompanyID) AND (TypeID = 3) END I've also tried: SELECT AdviserID, AdviserName FROM Advisers WHERE CASE @CompanyID WHEN 2 THEN (CompanyID = @CompanyID) ELSE (CompanyID = @CompanyID) AND (TypeID = 3) END and SELECT AdviserID, AdviserName FROM Advisers WHERE CASE WHEN (@CompanyID = 2) THEN (CompanyID = @CompanyID) ELSE (CompanyID = @CompanyID) AND (TypeID = 3) END I'd be very grateul to know (a) what the correct syntax for this is and (b) if it can be achieved using a parametised query, rather than a stored procedure. Thanks very much. Regards Gary