CASE Function Result With Result Expression Values (for IN Keyword)
I am trying to code a WHERE xxxx IN ('aaa','bbb','ccc') requirement but it the return values for the IN keyword changes according to another column, thus the need for a CASE function.
WHERE GROUP.GROUP_ID = 2 AND DEPT.DEPT_ID = 'D' AND WORK_TYPE_ID IN ( CASE DEPT_ID WHEN 'D' THEN 'A','B','C' <---- ERROR WHEN 'F' THEN 'C','D ELSE 'A','B','C','D' END )
I kept on getting errors, like
Msg 156, Level 15, State 1, Line 44Incorrect syntax near the keyword 'WHERE'.
which leads me to assume that the CASE ... WHEN ... THEN statement does not allow mutiple values for result expression. Is there a way to get the SQL above to work or code the same logic in a different manner in just one simple SQL, and not a procedure or T-SQL script.
View Complete Forum Thread with Replies
Related Forum Messages:
Table-valued User-defined Function: Commands Completed Successfully, Where Is The Result? How Can I See Output Of The Result?
Hi all, I copied the following code from Microsoft SQL Server 2005 Online (September 2007): UDF_table.sql: USE AdventureWorks; GO IF OBJECT_ID(N'dbo.ufnGetContactInformation', N'TF') IS NOT NULL DROP FUNCTION dbo.ufnGetContactInformation; GO CREATE FUNCTION dbo.ufnGetContactInformation(@ContactID int) RETURNS @retContactInformation TABLE ( -- Columns returned by the function ContactID int PRIMARY KEY NOT NULL, FirstName nvarchar(50) NULL, LastName nvarchar(50) NULL, JobTitle nvarchar(50) NULL, ContactType nvarchar(50) NULL ) AS -- Returns the first name, last name, job title, and contact type for the specified contact. BEGIN DECLARE @FirstName nvarchar(50), @LastName nvarchar(50), @JobTitle nvarchar(50), @ContactType nvarchar(50); -- Get common contact information SELECT @ContactID = ContactID, @FirstName = FirstName, @LastName = LastName FROM Person.Contact WHERE ContactID = @ContactID; SELECT @JobTitle = CASE -- Check for employee WHEN EXISTS(SELECT * FROM HumanResources.Employee e WHERE e.ContactID = @ContactID) THEN (SELECT Title FROM HumanResources.Employee WHERE ContactID = @ContactID) -- Check for vendor WHEN EXISTS(SELECT * FROM Purchasing.VendorContact vc INNER JOIN Person.ContactType ct ON vc.ContactTypeID = ct.ContactTypeID WHERE vc.ContactID = @ContactID) THEN (SELECT ct.Name FROM Purchasing.VendorContact vc INNER JOIN Person.ContactType ct ON vc.ContactTypeID = ct.ContactTypeID WHERE vc.ContactID = @ContactID) -- Check for store WHEN EXISTS(SELECT * FROM Sales.StoreContact sc INNER JOIN Person.ContactType ct ON sc.ContactTypeID = ct.ContactTypeID WHERE sc.ContactID = @ContactID) THEN (SELECT ct.Name FROM Sales.StoreContact sc INNER JOIN Person.ContactType ct ON sc.ContactTypeID = ct.ContactTypeID WHERE ContactID = @ContactID) ELSE NULL END; SET @ContactType = CASE -- Check for employee WHEN EXISTS(SELECT * FROM HumanResources.Employee e WHERE e.ContactID = @ContactID) THEN 'Employee' -- Check for vendor WHEN EXISTS(SELECT * FROM Purchasing.VendorContact vc INNER JOIN Person.ContactType ct ON vc.ContactTypeID = ct.ContactTypeID WHERE vc.ContactID = @ContactID) THEN 'Vendor Contact' -- Check for store WHEN EXISTS(SELECT * FROM Sales.StoreContact sc INNER JOIN Person.ContactType ct ON sc.ContactTypeID = ct.ContactTypeID WHERE sc.ContactID = @ContactID) THEN 'Store Contact' -- Check for individual consumer WHEN EXISTS(SELECT * FROM Sales.Individual i WHERE i.ContactID = @ContactID) THEN 'Consumer' END; -- Return the information to the caller IF @ContactID IS NOT NULL BEGIN INSERT @retContactInformation SELECT @ContactID, @FirstName, @LastName, @JobTitle, @ContactType; END; RETURN; END; GO ---------------------------------------------------------------------- I executed it in my SQL Server Management Studio Express and I got: Commands completed successfully. I do not know where the result is and how to get the result viewed. Please help and advise. Thanks in advance, Scott Chang
View Replies !
URGENT - My Error Or Bug? The Result Of The Expression Cannot Be Written To The Property. The Expression Was Evaluated, But
Error 3 Error loading MLS_AZ_PHX.dtsx: The result of the expression ""C:\sql_working_directory\MLS\AZ\Phoenix\Docs\Armls_Schema Updated 020107.xls"" on property "ConnectionString" cannot be written to the property. The expression was evaluated, but cannot be set on the property. c:documents and settingsviewmastermy documentsvisual studio 2005projectsm l sMLS_AZ_PHX.dtsx 1 1 "C:\sql_working_directory\MLS\AZ\Phoenix\Docs\Armls_Schema Updated 020107.xls" Directly using C:sql_working_directoryMLSAZPhoenixDocsArmls_Schema Updated 020107.xls as connectionString works However - I'm trying to deploy the package - and trying to use expression: @[User::DIR_WORKING] + "\Docs\Armls_Schema Updated 020107.xls" which causes the same error to occur (Same error with other Excel source also: Error 5 Error loading MLS_AZ_PHX.dtsx: The result of the expression "@[User::DIR_WORKING] + "\Docs\Armls_SchoolCodesJuly06.xls"" on property "ConnectionString" cannot be written to the property. The expression was evaluated, but cannot be set on the property. c:documents and settingsviewmastermy documentsvisual studio 2005projectsm l sMLS_AZ_PHX.dtsx 1 1 )
View Replies !
3 / 2=1? Strange Result In Expression...HELP!
Hi Folks!I have a strange thing happening; I have a field that Counts the number ofrecords and another field that shows the number of clients(Count(RecordID)=3 and NoOfClients=2) When I do a simple expression"Count(RecordID)/NoOfClients" the expected result should be 1.5. Insteadthe result I get is 1. Any ideas?Thanks!Rick
View Replies !
Problem Using Result From CASE In Another CASE Statement
I have a view where I'm using a series of conditions within a CASE statement to determine a numeric shipment status for a given row. In addition, I need to bring back the corresponding status text for that shipment status code. Previously, I had been duplicating the CASE logic for both columns, like so: Code Block...beginning of SQL view... shipment_status = CASE [logic for condition 1] THEN 1 WHEN [logic for condition 2] THEN 2 WHEN [logic for condition 3] THEN 3 WHEN [logic for condition 4] THEN 4 ELSE 0 END, shipment_status_text = CASE [logic for condition 1] THEN 'Condition 1 text' WHEN [logic for condition 2] THEN 'Condition 2 text' WHEN [logic for condition 3] THEN 'Condition 3 text' WHEN [logic for condition 4] THEN 'Condition 4 text' ELSE 'Error' END, ...remainder of SQL view... This works, but the logic for each of the case conditions is rather long. I'd like to move away from this for easier code management, plus I imagine that this isn't the best performance-wise. This is what I'd like to do: Code Block ...beginning of SQL view... shipment_status = CASE [logic for condition 1] THEN 1 WHEN [logic for condition 2] THEN 2 WHEN [logic for condition 3] THEN 3 WHEN [logic for condition 4] THEN 4 ELSE 0 END, shipment_status_text = CASE shipment_status WHEN 1 THEN 'Condition 1 text' WHEN 2 THEN 'Condition 2 text' WHEN 3 THEN 'Condition 3 text' WHEN 4 THEN 'Condition 4 text' ELSE 'Error' END, ...remainder of SQL view... This runs as a query, however all of the rows now should "Error" as the value for shipment_status_text. Is what I'm trying to do even currently possible in T-SQL? If not, do you have any other suggestions for how I can accomplish the same result? Thanks, Jason
View Replies !
Result Of Expression Cannot Be Written To A Property
Hello, We're trying to launch a SSIS package throw a webservice. This WebService loads a configuration file with "myPackage.ImportConfigurationFile(pathConfig)" and assigns values to some variables with "myPackage.Variables.Item(Parameters.Keys.Item(i)).Value = Parameters.Item(i)". Seems to work. I we execute the webmethod of the WebService, this works but only when we execute first time, the SSIS finished succesfully. But when we execute a second time the Webmethod, we've a lot of failure with messages: The result of the expression "@[User::Email]" on property "ToLine" cannot be written to the property. The expression was evaluated, but cannot be set on the property.The result of the expression ""The Import of " + @[User::ExcelFile]+ " is successful"" on property "MessageSource" cannot be written to the property. The expression was evaluated, but cannot be set on the property. Thx for your help
View Replies !
Expression To Show Result 12 Months Back
I´m creating a report in SSRS 2005 where you can filter after month and year. The result is the total sale for that particular month. What I want to do, is adding an extra column to compare with the result in the same month last year. F.eks. say that I choose january 2008 I would like to see the results for january 2007. I thought of writing an expression to do that, but as that isn't my stronges side I would appreciate some help
View Replies !
How Can I Get The Result In This Case?
Hi. there, Could you help me out? The data in my table is as belows, MOV_TITLE PLACE =============== ================ Fifteen Minutes Washington Pearl Harbor LA Pearl Harbor Seattle Terminator Houston The Lost Soul New York The result I want is as follows. MOV_TITLE PLACE =============== ================ Pearl Harbor LA Seattle In movie_title, I want to remove duplicate one and select only one but all data for place. Is this possible with SQL? Thanks in advance,
View Replies !
How Can I Get The Result In This Case?
Hi. there, Could you help me out? The data in my table is as belows, MOV_TITLE PLACE =============== ================ Fifteen Minutes Washington Pearl Harbor LA Pearl Harbor Seattle Terminator Houston The Lost Soul New York The result I want is as follows. MOV_TITLE PLACE =============== ================ Pearl Harbor LA Seattle In movie_title, I want to remove duplicate one and select only one but all data for place. Is this possible with SQL? Thanks in advance,
View Replies !
How Can I Get The Result In This Case?
Sorry for the mess in previous two message. Hi. there, Could you help me out? The data in my table with mov_title, place as columns, are as belows, MOV_TITLE ========= Fifteen Minutes Pearl Harbor Pearl Harbor Terminator The Lost Soul PLACE ========== Washington LA Seattle Houston New York The result I want is as follows. MOV_TITLE ============ Pearl Harbor PLACE ======== LA Seattle In movie_title, I want to remove duplicate one and select only one but all data for place. Is this possible with SQL? Thanks in advance,
View Replies !
CASE With More Than One Result
Hello, I have a business rule that says if PROD = ''XCDD' and ProductRollUp = 'XCSH' Then BillingType = 'Express Cash' or 'Payment Services'. Is there a way to represent that rule with a CASE statement? Thank you for your help! cdun2
View Replies !
Retrieving Result Set From Dynamically Called Stored Procedure Or Function In A Function
Is there any way I can retrieve the result set of a Stored Procedurein a function.ALTER FUNCTION dbo.fn_GroupDeviceLink(@groupID numeric)RETURNS @groupDeviceLink TABLE (GroupID numeric, DeviceID numeric)ASBEGINDeclare @command nvarchar(255)SELECT @command = Condition// @command is an SQL string or stored procedue nameFROM DeviceGroupWHERE GroupID = @groupIDINSERT @groupDeviceLinkEXEC @commandRETURNENDIs there any way i can do anything like this. @command is a variableholding the name of a stored produre. I need to run that storedprocure and return the values in such a way that they can be used in aSELECT StatementMy goal is SELECT * FROM Device INNER JOINdbo.fn_GroupDeviceLink(@groupID) ON ....this fn_GroupDeviceLink should run the proper stored procedure andreturn the values. What i also want to do is play with that result setof the specific stored procedure before i return it. Is this possible?If not, what is the work arround?ThanksMark
View Replies !
SSIS Expression Result Limit Of 4000 Bytes
I have a package with an input column that is varchar(8000). I want to strip the first byte off of this column and put it in one result column and the remainder of the field I want to go to a second column. If the input column is an empty string, I want to return NULL. Pulling the first byte off works fine, no issues, however putting the remainder of the input column into an output column is giving me a little trouble. If I use this expression: LEN(FLD1) == 0 ? NULL(DT_WSTR,1) : SUBSTRING(FLD1, 2, LEN(FLD1) - 1)) I get an error that says my expression evaluates to a string of greater than 4000 bytes. If I do this instead: LEN(FLD1) == 0 ? NULL(DT_WSTR,1) : RTRIM(SUBSTRING(FLD1, 2, 7999)) The expression passes muster but I get the warning that I will be truncating the column at 4000 bytes. In actuality, I don't care if the result column is truncated after 4000 bytes. I find the second solution to be a bit clunky and I'm wondering if anyone can give me a reason why the first solution won't evaluate but the second will?
View Replies !
Set Variable Based On Result Of Procedure OR Update Columns Fromsproc Result
I need to send the result of a procedure to an update statement.Basically updating the column of one table with the result of aquery in a stored procedure. It only returns one value, if it didnt Icould see why it would not work, but it only returns a count.Lets say I have a sproc like so:create proc sp_countclients@datecreated datetimeasset nocount onselect count(clientid) as countfrom clientstablewhere datecreated > @datecreatedThen, I want to update another table with that value:Declare @dc datetimeset @dc = '2003-09-30'update anothertableset ClientCount = (exec sp_countclients @dc) -- this line errorswhere id_ = @@identityOR, I could try this, but still gives me error:declare @c intset @c = exec sp_countclients @dcWhat should I do?Thanks in advance!Greg
View Replies !
Problem Assigning SQL Task Result To A Variable - Select Count(*) Result From Oracle Connection
I have an Execute SQL Task that executes "select count(*) as Row_Count from xyztable" from an Oracle Server. I'm trying to assign the result to a variable. However when I try to execute I get an error: [Execute SQL Task] Error: An error occurred while assigning a value to variable "RowCount": "Unsupported data type on result set binding Row_Count.". Which data type should I use for the variable, RowCount? I've tried Int16, Int32, Int64. Thanks!
View Replies !
In-Line Table-Valued Function: How To Get The Result Out From The Function?
Hi all, I executed the following sql script successfuuly: shcInLineTableFN.sql: USE pubs GO CREATE FUNCTION dbo.AuthorsForState(@cState char(2)) RETURNS TABLE AS RETURN (SELECT * FROM Authors WHERE state = @cState) GO And the "dbo.AuthorsForState" is in the Table-valued Functions, Programmabilty, pubs Database. I tried to get the result out of the "dbo.AuthorsForState" by executing the following sql script: shcInlineTableFNresult.sql: USE pubs GO SELECT * FROM shcInLineTableFN GO I got the following error message: Msg 208, Level 16, State 1, Line 1 Invalid object name 'shcInLineTableFN'. Please help and advise me how to fix the syntax "SELECT * FROM shcInLineTableFN" and get the right table shown in the output. Thanks in advance, Scott Chang
View Replies !
'#Error' In RS2005 For MDX Expression In Preview Tab But Data Tab Gives Proper Result
Hi, I have a calculated member with a simple MDX expression which returns the number of open accounts. The problem is this expression gives proper results when I test in the SSAS (Analysis services) browser. It even works fine if I used Excel pivot table. But when I use the same expression in RS2005 in the data tab it shows me proper results but when I preview in the preview tab it shows '#Error' for the data in the Matrix. This occurs when I add the "Coalesceempty" function in the MDX expression which replaces the NULL values with 0. The MDX expression I am using is: Case When IsEmpty([Measures].[Account Count]) Then Null Else COALESCEEMPTY(([Measures].[Account Count], [Account].[Account Close Flag].&[False]), 0) End Any thoughts would be greatly appreciated. Thanks.
View Replies !
Saving Query Result To A File , When View Result Got TLV Error
HI, I ran a select * from customers where state ='va', this is the result... (29 row(s) affected) The following file has been saved successfully: C:outputcustomers.rpt 10826 bytes I choose Query select to a file then when I tried to open the customer.rpt from the c drive I got this error message. I am not sure why this happend invalid TLV record Thanks for your help Ali
View Replies !
End Result Is Main Query Results Ordered By Nested Result
As the topic suggests I need the end results to show a list of shows and their dates ordered by date DESC. Tables I have are structured as follows: SHOWS showID showTitle SHOWACCESS showID remoteID VIDEOS videoDate showID SQL is as follows: SELECT shows.showID AS showID, shows.showTitle AS showTitle, (SELECT MAX(videos.videoFilmDate) AS vidDate FROM videos WHERE videos.showID = shows.showID) FROM shows, showAccess WHERE shows.showID = showAccess.showID AND showAccess.remoteID=21 ORDER BY vidDate DESC; I had it ordering by showTitle and it worked fine, but I need it to order by vidDate. Can anyone shed some light on where I am going wrong? thanks
View Replies !
CASE Does Not Give Correct Result
How do I automatically assign a new cardcode-number? (according to the following formula: highest existing number + 1) Scenario: -There are two types of business partners: Customers and Suppliers. -Customers have the value 'C' in the colomn CardType. -Suppliers have the value 'S' in the colomn CardType. -Customers have the following syntax 'C123456' in the colomn CardCode. -Suppliers have the following syntax 'S123456' in the colomn CardCode. -Existing CardCode-values in the DB for the Customers: C000001 - C100599. -Existing CardCode-values in the DB for the Suppliers: S000001 - S200199. The idea is that when a user creates a new business partner, the CardCode should be automatically filled when a new assigned number (highest existing number + 1), according to the value that is selected in CardType (either the letter 'C' or 'S'). What's been done so far: SELECT top 1 (CASE WHEN CardType='C' THEN (SELECT top 1 'C' + '' + cast((substring(T0.CardCode, 2, 7) + 1) as varchar) as [nummer] FROM OCRD T0 WHERE T0. CardCode like 'C%' AND T0. CardType='C' order BY T0.CardCode desc FOR BROWSE) WHEN CardType='S' THEN (SELECT top 1 'S' + '' + cast((substring(T0.CardCode, 2, 7) + 1) as varchar) as [nummer] FROM OCRD T0 WHERE T0. CardCode like 'S%' AND T0. CardType='S' order BY T0.CardCode desc FOR BROWSE) END) FROM OCRD T0 The current result: The result that it gives is 'C100600'. The problem however is that it always gives this result and does not take into account what has been selected in CardType. When I add the following: "order BY T0.CardCode desc FOR BROWSE" it gives the result 'S200200'. So, what does work is that it takes the highest existing value and adds 1. But what doesn't work is the taking account what value is selected in CardType. Does anyone know how I can make this work?
View Replies !
How To Pass Result From Case Statement To An Equation?
How to get the CASE results highlighted in BOLD into this equation; "(LogOut - LogIn) + (LunchBreak) -(AMBreak) + (PMBreak) AS TimeWorked" ? Thank you. CREATE VIEW dbo.vwu_ReportViewASSELECT EmployeeID , LastName , FirstName , LocationCode , UserID , Today , Login , AMBreakOut , AMBreakIn , CASE WHEN ISNULL(DATEDIFF(Minute, AMBreakOut, AMBreakIn),0) >= 0 AND ISNULL(DATEDIFF(Minute, AMBreakOut, AMBreakIn),0) <= 19 THEN '0' WHEN ISNULL(DATEDIFF(Minute, AMBreakOut, AMBreakIn),0) >= 20 AND ISNULL(DATEDIFF(Minute, AMBreakOut, AMBreakIn),0) <= 34 THEN '15' WHEN ISNULL(DATEDIFF(Minute, AMBreakOut, AMBreakIn),0) >= 35 AND ISNULL(DATEDIFF(Minute, AMBreakOut, AMBreakIn),0) <= 49 THEN '30' WHEN ISNULL(DATEDIFF(Minute, AMBreakOut, AMBreakIn),0) > = 50 AND ISNULL(DATEDIFF(Minute, AMBreakOut, AMBreakIn),0) <= 64 THEN '45' ELSE '60' END AS AMBreak , LunchOut , LunchIn , CASE WHEN ISNULL(DATEDIFF(Minute, LunchOut, LunchIn),0) >= 0 AND ISNULL(DATEDIFF(Minute, LunchOut, LunchIn),0) <= 66 THEN '0' WHEN ISNULL(DATEDIFF(Minute, LunchOut, LunchIn),0) >= 67 AND ISNULL(DATEDIFF(Minute, LunchOut, LunchIn),0) <= 81 THEN '15' WHEN ISNULL(DATEDIFF(Minute, LunchOut, LunchIn),0) >= 82 AND ISNULL(DATEDIFF(Minute, LunchOut, LunchIn),0) <= 96 THEN '30' WHEN ISNULL(DATEDIFF(Minute, LunchOut, LunchIn),0) >= 97 AND ISNULL(DATEDIFF(Minute, LunchOut, LunchIn),0) <= 111 THEN '45' WHEN ISNULL(DATEDIFF(Minute, LunchOut, LunchIn),0) >= 112 AND ISNULL(DATEDIFF(Minute, LunchOut, LunchIn),0) <= 126 THEN '60' ELSE '75' END AS LunchBreak, PMBreakOut , PMBreakIn , CASE WHEN ISNULL(DATEDIFF(Minute, PMBreakOut, PMBreakIn),0) >= 0 AND ISNULL(DATEDIFF(Minute, PMBreakOut, PMBreakIn),0) <= 19 THEN '0' WHEN ISNULL(DATEDIFF(Minute, PMBreakOut, PMBreakIn),0) >= 20 AND ISNULL(DATEDIFF(Minute, PMBreakOut, PMBreakIn),0) <= 34 THEN '15' WHEN ISNULL(DATEDIFF(Minute, PMBreakOut, PMBreakIn),0) >= 35 AND ISNULL(DATEDIFF(Minute, PMBreakOut, PMBreakIn),0) <= 49 THEN '30' WHEN ISNULL(DATEDIFF(Minute, PMBreakOut, PMBreakIn),0) >= 50 AND ISNULL(DATEDIFF(Minute, PMBreakOut, PMBreakIn),0) <= 64 THEN '45' ELSE '60' END AS PMBreak , Logout , Comments , LoginLogon , AMBreakOutLogon , AMBreakInLogon , LunchOutLogon , LunchInLogon , PMBreakOutLogon , PMBreakInLogon , LogoutLogon ,(LogOut - LogIn) + (LunchBreak) -(AMBreak) + (PMBreak) AS TimeWorked
View Replies !
Case Stmt Returns Duplicate Result
Hi there, The following is my table whereby i have joined projects table with issue table (this is 1 to many relationship). I have the following query: SELECT odf.mbb_sector sectorid, SUM(case when odf.mbb_projecttype = 'lkp_val_appl' then 1 else 0 end) total_appl, SUM(case when odf.mbb_projecttype = 'lkp_val_infrastructure' then 1 else 0 end) total_infra, SUM(case when odf.mbb_projecttype = 'lkp_val_eval' then 1 else 0 end) total_eval, SUM(case when odf.mbb_projecttype = 'lkp_val_subproject' then 1 else 0 end) total_subprj, SUM(case when odf.mbb_projecttype = 'lkp_val_nonit' then 1 else 0 end) total_nonit, SUM(case when odf.mbb_projecttype = 'lkp_val_adhocrptdataextract' or odf.mbb_projecttype = 'lkp_val_productionproblem' or odf.mbb_projecttype = 'lkp_val_maintwoprogchange' then 1 else 0 end) total_others, COUNT(distinct prj.prid) total_prj FROM PRJ_PROJECTS AS PRJ, SRM_PROJECTS AS SRM, ODF_CA_PROJECT AS ODF LEFT JOIN RIM_RISKS_AND_ISSUES AS RRI ON RRI.pk_id = odf.id WHERE prj.prid = srm.id AND srm.id = odf.id AND srm.is_active =1 AND odf.mbb_projecttype not in ('lkp_val_budget','lkp_val_itpc') AND odf.mbb_funcunit = 'lkp_val_operation' GROUP BY odf.mbb_sector which returns me the following result : . The problem is at the lkp_val_infosystem where it returns 3 instead of 1 in the total_infra column. How do I correct my case stmt to return the correct no of projects breakdown by different project type? Currently, only the total_prj which returns correct data. Thanks
View Replies !
Getting SUM Function Result
Hello,In the project I'm working on, I need to add up all rows data for onecolumn. So, I have this code:$getprodcount = mysql_query("SELECT SUM(qty) FROM purchase");$numproducts=$getprodcount;Later on, I have this code: <?php print $numproducts; ?>What is being printed is Resource id #5...not the numeric value of what issupposed to be a sum. What is wrong? I am assuming taht resource id #5 is apointer of some sorts to the number I am looking for, but how do you getthe actual sum number?Thanks in advance!--Message posted via http://www.sqlmonster.com
View Replies !
Function And One Result Set
I have an function executed like that: select top 1 * from f_Function1('XXX',2099,99) ORDER BY ef DESC I have about 400 XXX values. I execute function individually for them but normally i get results in individual result sets. select top 1 * from f_Function1('XXX1',2099,99) ORDER BY ef DESC select top 1 * from f_Function1('XXX2',2099,99) ORDER BY ef DESC select top 1 * from f_Function1('XXX3',2099,99) ORDER BY ef DESC I want all 400 results in one result set. What should i do? Thanks in advance.
View Replies !
Index On Result Of Function
I have a table with about 28 million records in it. Each row has an ID (PK), logged (datetime), IP varchar(15) The data grows at about 14 million records per year. I'm going to be running queries on the table that extract the MONTH or YEAR from the logged column. In Foxpro tables I would have created indexes on YEAR(logged) and MONTH(logged) so my queries would run faster. Is this possible/necessary in SQL Server?
View Replies !
How To Get Result In Decimal Using AVG Function
Hello Sir I am working on a Teacher Evaluation Project. In my database I store results from 1-5 as evaluation indicators. I apply AVG() function on the result column. The result of the query is in integer values (i.e) 4, 3 2 or 5. I want the resutl up to two decimal places. How can i write the query to get the result in decimal form? Shahbaz Hassan Wasti
View Replies !
Compare Values In Result Set.
This is my first post and I am probably not using the correct terminology but I will try. I want to compare the value of one of my fields in a result set to the value of the same column/field, but from the previous row in the result set. I am trying to identify the row in the result set when the value in a specified column changes value. I want to identify this row by placing a 1 in the last column. If that value did not change, then place a 0 in the last column. I am not sure if this will make sense to anyone out there. Please let me know if more clarification is needed and I will try to provide it. Thanks for all your help in advance. Don
View Replies !
SQL Query - Using Result Of Create Function
I created a function that will return from OpenDataSource('.....') tablename where ... is fully populated. However, I can't figure out how to use it? For example select functiona (parameter) as data_src this returns the "from" statement above I then try to run select * data_src So how do I reference the contents of data_src in the select? Thanks for any help
View Replies !
How To Return The Result Of An EXEC From A Function
Hi, I am trying to find a way to return the result of an EXEC(*sqlstring*) from a function. I can return the tsql but not the result of an execute. This is my function: ALTER FUNCTION [dbo].[ReturnPickItemValue] ( -- Add the parameters for the function here @TypeID int, @CaseID int ) RETURNS varchar(max) AS BEGIN -- Declare the return variable here DECLARE @RTN varchar(max) IF(SELECT IncludeDates FROM TBL_LU_PICK WHERE PickTypeID = @TypeID) = 1 BEGIN SET @RTN = 'SELECT PickItem I + CASE D.IsStartDateEstimated WHEN 0 THEN CAST(StartDate as varchar) ELSE CAST(dbo.ReturnEstimatedDate(D.IsStartDateEstimated, 0) as varchar) END + CASE D.IsEndDateEstimated WHEN 0 THEN CAST(EndDate as varchar) ELSE CAST(dbo.ReturnEstimatedDate(D.IsEndDateEstimated, 1) as varchar) END FROM TBL_LU_PICK L INNER JOIN TBL_Pick_Items I ON I.PickTypeID = L.PickTypeID INNER JOIN TBL_PICK P ON P.PickItemID = I.PickItemID LEFT JOIN TBL_PickDates D ON D.PickID = P.PickID WHERE L.PickTypeID = ' + CAST(@TypeID as varchar) + ' AND P.CaseID = ' + CAST(@CaseID as varchar) END ELSE BEGIN SET @RTN= 'SELECT I.PickItem FROM TBL_LU_PICK L INNER JOIN TBL_Pick_Items I ON I.PickTypeID = L.PickTypeID INNER JOIN TBL_Pick P ON P.PickItemID = I.PickItemID WHERE L.PickTypeID = ' + CAST(@TypeID as varchar) + ' AND CaseID = ' + CAST(@CaseID as varchar) END RETURN @RTN END Each time I try " RETURN EXEC(@RTN) " or something similar I get an error. I have tried executing the tsql and assigning the result to a varchar and returning that varchar but i get an error. Anyone with any ideas?
View Replies !
Comparing Result Set Values Of 2 Queries ??
Any assistance would be so helpful !! We have 2 tables.. lets call them INV and COST Table INV and COST have 3 related columns, namely ID,AMOUNT and VAT. As shown below... ID | AMOUNT | VAT ( INV TABLE ) 1 |20.125 |2.896 2 |10.524 |1.425 ID | AMOUNT | VAT ( COST TABLE ) 1 |20.125 |4.821 .... different to ID 1 in INV Table 2 |10.524 |1.425 If you look above, I need to sum the AMOUNT and VAT columns and get a value for each ID, then compare the two tables and get the ID's that have different values...in this case I would need a result saying ID1 as the total of INV TABLE ID1 (23.021) is different to the corresponding ID1 row in COST TABLE (24.946) Thats it ??? Please could someone out there offer some ideas ? THANKS JON
View Replies !
Comparing Result Set Values Of 2 Queries ??
Any assistance would be so helpful !! We have 2 tables.. lets call them INV and COST Table INV and COST have 3 related columns, namely ID,AMOUNT and VAT. As shown below... ID | AMOUNT | VAT ( INV TABLE ) 1 |20.125 |2.896 2 |10.524 |1.425 ID | AMOUNT | VAT ( COST TABLE ) 1 |20.125 |4.821 .... different to ID 1 in INV Table 2 |10.524 |1.425 If you look above, I need to sum the AMOUNT and VAT columns and get a value for each ID, then compare the two tables and get the ID's that have different values...in this case I would need a result saying ID1 as the total of INV TABLE ID1 (23.021) is different to the corresponding ID1 row in COST TABLE (24.946) Thats it ??? Please could someone out there offer some ideas ? THANKS JON
View Replies !
Comparing Result Set Values Of 2 Queries ??
Any assistance would be so helpful !! We have 2 tables.. lets call them INV and COST Table INV and COST have 3 related columns, namely ID,AMOUNT and VAT. As shown below... ID | AMOUNT | VAT ( INV TABLE ) 1 |20.125 |2.896 2 |10.524 |1.425 ID | AMOUNT | VAT ( COST TABLE ) 1 |20.125 |4.821 .... different to ID 1 in INV Table 2 |10.524 |1.425 If you look above, I need to sum the AMOUNT and VAT columns and get a value for each ID, then compare the two tables and get the ID's that have different values...in this case I would need a result saying ID1 as the total of INV TABLE ID1 (23.021) is different to the corresponding ID1 row in COST TABLE (24.946) Thats it ??? Please could someone out there offer some ideas ? THANKS JON
View Replies !
[effeciency] Specific Result Values
Hi. I had no idea what to name the topic so I hope this is ok. I feel like I am losing it, even though I am still learning SQL Server - I dont use it much in terms of technical/complex queries and so on but I do use SQL on a regular (almost) basis. I am all about making sure it is secure and effecient and performance and so on - just to give a bit of background about myself. Say for instance I have an ASP.NET website, which I have developed a discussion board from scratch using SQL Server to store all the information. Say for instance, we have a topic, and that topic will be "locked". Would I be correct in saying that on such a table, "Topics", there should be a field which is known as "ActiveStatus" or "IsLocked", and depending on if the thread is locked or not, that value is set on the table field? Am I correct in saying this? If not - then what is the correct way of stating/retrieving if the topic is locked, in other words, what is the best way to have control over the thread so you can lock the topic? I cannot think of another way but to store this one value in SQL on this topic table, along with other fields. I would then get the result by calling the procedure from ASP.NET and accordingly, set an image button on the webpage to either "locked" or "post reply" Sorry for being silly, but I want to confirm if I am about to do this correctly or not. I want to make sure I am doing the best practice all the time, and enjoy doing it naturally. What is the best design/decision on such a scenario/situation? Many thanks for your input, I greatly appreciate it! :-)
View Replies !
Removing Null Values From A Result Set
Hi, I have following query which is returing null values along with other values. Could you please tell me how I can restrict to not to return null values SELECT [Measures].[Total Hours] ON 0, [Employee].[Hierarchy].[Employee Key]ON 1 FROM[Labor Metrics] Thanks, Prudhvi
View Replies !
Aggregate Function For Select Statement Result?
Ok, for a bunch of cleanup that i am doing with one of my Portal Modules, i need to do some pretty wikid conversions from multi-view/stored procedure calls and put them in less spid calls. currently, we have a web graph that is hitting the sql server some 60+ times with data queries, and lets just say, thats not good. so far i have every bit of data that i need in a pretty complex sql call, now there is only one thing left to do. Problem: i need to call an aggregate count on the results of another aggregate function (sum) with a group by. *ex: select count(select sum(Sales) from ActSales Group by SalesDate) from ActSales This is seriously hurting me, because from everything i have tried, i keep getting an error at the second select in that statement. is there anotherway without using views or stored procedures to do this? i want to imbed this into my mega sql statement so i am only hitting the server up with one spid. thanks, Tom Anderson Software Engineer Custom Business Solutions
View Replies !
Strange Result - Minus Result -1
help strange result whan i do this Code Snippet SELECT unit_date, unit, ISNULL(NULLIF ((unit + DATEDIFF(mm, GETDATE(), unit_date)) % 4, 0), 4) AS new_unit FROM dbo.empList i try to get next unit value to next month why i get this -1 on date 01/01/2008 1 -1 unit_date unit new_unit 01/02/2008 2 1 01/02/2008 1 4 01/01/2008 1 -1 01/02/2008 1 4 21/01/2008 1 -1 21/01/2008 1 -1 01/02/2008 1 4 TNX
View Replies !
How To Use A Function To Format And Display Result From Data Reader
Hi guys n gals ! I am having a few problems manipulating the results of my data reader,To gather the data I need my code is: // database connection SqlConnection dbcon = new SqlConnection(ConfigurationManager.AppSettings["dbcon"]); // sql statement to select latest news item and get the posters name SqlCommand rs = new SqlCommand("select * from tblnews as news left join tblmembers as members ON news.news_posted_by = members.member_idno order by news.news_idno desc", dbcon); // open connection dbcon.Open(); // execute SqlDataReader dr = rs.ExecuteReader(); // send the data to the repeater repeater_LatestNews.DataSource = dr; repeater_LatestNews.DataBind(); Then I am using: <%#DataBinder.Eval(Container.DataItem, "news_comments")%> in my repeater.What I need to do is pass the "news_comments" item to a function I created which will then write the result. The code for my function is: // prevent html public string StripHtml(string data) { // grab the data string theData = data; // replace < with &alt; theData = Regex.Replace(theData, "<", "<"); // return result return theData; } But I am having problms in doing this,Can anyone point me in the right direction on what I should be doing ???
View Replies !
Converting Result Of Aggregate Function Calculation To A Double (C#)
I've put a SelectCommand with an aggregate function calculation and AS into a SqlDataSource and was able to display the result of the calculation in an asp:BoundField in a GridView; there was an expression after the AS (not sure what to call it) and that expression apparently took the calculation to the GridView (so far so good). If I write the same SELECT statement in a C# code behind file, is there a way to take the aggregate function calculation and put it into a double variable? Possibly, is the expression after an AS something that I can manipulate into a double variable? My end goal is to insert the result of the calculation into a database. What I have so far with the SelectCommand, the SqlDataSource and the GridView is shown below in case this helps: <asp:GridView class="gridview" ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="lbsgalDataSource"> <Columns> <asp:BoundField DataField="Formulation" HeaderText="Formulation" SortExpression="Formulation" /> <asp:BoundField DataField="lbs" HeaderText="lbs" SortExpression="lbs" /> <asp:BoundField DataField="gal" HeaderText="gallons" SortExpression="gal" /> <asp:BoundField DataField="density" HeaderText="density" SortExpression="density" /> </Columns> </asp:GridView> <asp:SqlDataSource ID="lbsgalDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT a.Formulation, SUM (a.lbs) AS lbs, SUM ((a.lbs)/(b.density)) AS gal, ( ( SUM (a.lbs) ) / ( SUM ((a.lbs)/(b.density)) ) ) AS density FROM Formulations a INNER JOIN Materials b ON a.Material=b.Material WHERE Formulation=@Formulation GROUP BY Formulation"> <selectparameters> <asp:controlparameter controlid="DropDownList1" name="Formulation" propertyname="SelectedValue" type="String" /> </selectparameters> </asp:SqlDataSource>
View Replies !
Passing MS SQL2005 Query Result Into Javascript Function
I'm selecting the last latitude & longitude input from my database to put into the Google maps javascript function. This is how I retrieve the longitude: <asp:SqlDataSource ID="lon" runat="server" ConnectionString="<%$ ConnectionStrings:LocateThis %>" SelectCommand= "SELECT @lon= SELECT [lon] lon FROM [location] WHERE time = (SELECT MAX(time) FROM [location] where year < 2008)"> </asp:SqlDataSource> I wish to input the latitude & longitude into the JAVASCRIPT function (contained in the HTML head before the ASP) something like this: var map = new GMap2(document.getElementById("map"));var lat = <%=lat%>;var lon = <%=lon%>;var center = new GLatLng(lat,lon);map.setCenter(center, 13); However, lat & long do not contain the retrieved result but rather a useless System.something string. How do I assign the retrieved results to these variables and port them over to Javascript as required? Many thanks!
View Replies !
Problem Passing UDF Scalar Result To UDF Table Function
I'm having difficulties invoking a user defined table function,when passing to it a parameter that is the result of anotheruser defined function.My functions are defined like so:drop function dbo.scalar_funcgocreate function dbo.scalar_func()returns intbeginreturn 1endgodrop function dbo.table_funcgocreate function dbo.table_func(@p int)returns tablereturn (select @p as id )goGiven the above, I can do the following:Select from the scalar function works:1> select dbo.scalar_func() as scalar_result2> goscalar_result-------------1Selecting from the table function works, if i pass aconstant value (or a variable)1> select id from dbo.table_func(1)2> goid-------------1But, if I try to pass the table function the return valueof the scalar function in one call, it doesn't work,producing the following error:1> select id from dbo.table_func( dbo.scalar_func() )2> goMsg 170, Level 15, State 1, Line 1Line 1: Incorrect syntax near '.'.What am I missing here?Thanks kindly
View Replies !
I Want To Show OpenQuery() Result With Local Table Values
Hi, I have two queries as under:QUERY 1:SELECT * FROM OPENQUERY(MYSERVER, 'SELECT * FROM SCOPE() WHERE FREETEXT(''Text to Search'')') AS DocsQUERY 2:SELECT MediaID, LawID, LawDate, Agreement, Name, NameSearch, LawType, LawNo, RegID, IssueNo, AttachmentFrom Dept_LegalLawINNER JOIN Dept_LegalMinistries ON Dept_LegalLaw.RegID = Dept_LegalMinistries.RegIDINNER JOIN Dept_LegalLawType ON Dept_LegalLaw.LawID = Dept_LegalLawType.LawIDWHERE 1=1 AND 1=1 AND 1=1 AND 1=1 AND 1=1 AND 1=1 AND 1=1 AND 1=1 AND 1=1 AND 1=1both queries are working fine separately and I can generate the desired results separately, but I cannot merge them to get one single result for example, after a FREETEXT search I want to get some values from my local table (Query2) to display as one result. Like in Query1 FREETEXT will search the web page based on the given text and in Query2 will select the remaining data from the local database (Title, ID, Name etc etc).Try many thing but no success yet.Need urgent help.Thanks
View Replies !
Need Sql To Return The Result Of A Query As Comma Seperated Values.
Hi, I need a sql that returns the query result as comma seperated list of values, instead of several rows. Below is the scenario... Table Name - Customer Columns - CustomerID, Join DateSay below is the data of Customer table ...CustomerID JoinDate1 04/01/20052 01/03/20033 06/02/20044 01/05/20025 09/07/2005Now i want to retrieve all the customerid's who have joined this year. Below is the query that i use for this case.Select CustomerID from Customer where JoinDate between '01/01/2005' and GetDate()This gives the below result as two rows.CustomerID15But i need to get the result as '1,5' (comma seperated list of resulting values).Any help is highly appreciatedThanks in AdvanceRamesh
View Replies !
Storing Values Into Variable From A Distributed Query Result
Hi. I am trying to store the column value to a variable from a distributed query. The query is formed on the fly. i need to accomplish something like this declare @id int declare @columnval varchar(50) declare @query varchar(1024) @Query = "select @columnval = Name from server.database.dbo.table where id ="+convert(varchar,@ID) exec (@query) print @Columnname -MAK
View Replies !
Function With Expression To Return Values
I have created a function to return values, which works fine, but I can't do calculations in it. CREATE FUNCTION [dbo].[tf_Asset_Portfolio](@deal_id int, @as_of_date datetime) RETURNS TABLE AS RETURN ( SELECT DISTINCT dbo.Assets.issue_id, SUM(DISTINCT dbo.Assets.par_amount) AS par_amount, SUM(DISTINCT dbo.Assets.par_amount) AS market_value FROM dbo.Issue INNER JOIN dbo.Assets ON dbo.Issue.issue_id = dbo.Assets.issue_id INNER JOIN dbo.Issuer_Rating_History ON dbo.Issue.issuer_id = dbo.Issuer_Rating_History.issuer_id WHERE (dbo.Issuer_Rating_History.as_of_date <= @as_of_date) GROUP BY ALL dbo.Assets.issue_id, dbo.Assets.deal_id, dbo.Issue.default_date HAVING (dbo.Assets.deal_id = @deal_id) ) I need to do calculations on market value based on the default date. If default date isn't specified then it should be 100% of par amount. If default date is less than one year ago - 65% of the par_amount. If default date is one or more years ago - 0. I have no idea about how to do this and everything I try wont work. I created another function to do the calculations and this seems to work, but it only does one record instead of all of them. CREATE FUNCTION dbo.tf_Asset_Portfolio2 (@deal_id int, @as_of_date datetime) RETURNS @Market TABLE (issue_id int, par_amount money, market_value money) AS BEGIN DECLARE @ReturnDate datetime DECLARE @DD datetime DECLARE @PA money DECLARE @MV money DECLARE @ID int DECLARE @DateD int SELECT TOP 1 @ReturnDate = LAST_BATCH FROM master..sysprocesses WHERE SPId = @@SPID SELECT @ID = issue_id FROM Assets WHERE Assets.deal_id = @deal_id SELECT @PA = SUM(DISTINCT par_amount) FROM Assets WHERE Assets.issue_id = @ID AND Assets.deal_id = @deal_id SELECT @DD = default_date FROM Issue WHERE Issue.issue_id = @ID SET @DateD = DateDiff("yyyy", @DD, @ReturnDate) If @DD = Null BEGIN SET @MV = @PA END Else If @DD > @ReturnDate BEGIN SET @MV = @PA END Else If @DateD < 1 BEGIN SET @MV = @PA * .65 END Else If @DateD >= 1 BEGIN SET @MV = 0 END insert into @Market (issue_id, par_amount, market_value) values (@ID,@PA,@MV) RETURN END I need to combine the functionality of being able to return mutliple records that isn't in the 2nd function and being able to calculate the market value which isn't in the first one. Please help. Thank you in advance.
View Replies !
Table-Valued Function Result Vs. Calculation Table
I need to return a table of values calculated from other tables. I have about 10 reports which will use approx. 6 different table structures. Would it be better performance wise to create a physical table in the database to update while calculating using an identity field to id the stored procedure call, return the data and delete the records. For Example: DataUserID, StrVal1,Strval2,StrVal4,IntVal1,IntVal2,FloatVal1... Or using a table-valued function to return a temp table as the result. I just dont know which overhead is worst, creating a table per function call, or using a defined table then deleting the result set per sp call.
View Replies !
|