The query below gets percentage of coils for a location by anneal cycle. It does this correctly (ie, if you change count(*)/b.total to count(*), b.total ... show both columns, the numbers its pulling are correct), but in its current state (trying to divide count by total), it always returns a zero (no decimal values).
If I change that section to : (count(*)*100/ b.total*100)/100, I get integer percentages: no decimals (this is a problem because some records round off to zero). I'm pretty sure this is the entire problem (why I'm getting zeros as written below), but I don't have a clue how to fix it. Is this some kind of server setting that allows the query to only return decimal values or something?
select a.department, a.cycle, count(*)/ b.total percentage from inventory a join (select department, count(*) total from inventory where location not like 'bas%' and archived = 0 and quality_code = 'p' group by department) b on a.department = b.department where a.archived = 0 and a.quality_code = 'p' and location not like 'bas%' group by a.department, a.cycle, b.total order by a.department, a.cycle
I have a field of type Real in my SQL 2K database. I stored a value of..35 in the field.When I "Open Table"->"Return All Rows" in the Enterprise Manager I getback .35 for the field value.I went to The SQL Query Analyzer and executed the following T-SQL:SELECT fieldFROM tableI got back 0.34999999 for the field.When running stored procs against the field I also get back 0.34999999.This is causing problems in my app. I can use the Round T-SQLstatement to get back the value I expect, but this causes appdevelopment problems. For a goof I put 1.35 in the field and T-SQL didreturn 1.35. This problem only seems to occur with 0.nnn values. Ialso tried a float data type for the field but I had the same problemsI had with real.Why is T-SQL returning 0.34999999 for my field?
I have a stored procedure that does all the dirty work for me. I'm just having one issue. I need it to run the total number of RECORDS, and I need it to return the total number of new records for TODAY. Here is part of the code:SELECT COUNT(ID) AS TotalCount FROM CounterSELECT COUNT(*) AS TodayCount FROM Counter WHERE DATEPART(YEAR, visitdate) = Year(GetDate()) AND DATEPART(MONTH, visitdate) = Month(GetDate()) AND DATEPART(DAY, visitdate) = Day(GetDate())The statement works great, I just need to return TotalCount and TodayCount in one query. Is this possible?
I have a stored procedure that returns a numeric value. I wish to call this procedure from within another one and have the returned value stored against a declared variable. I'm struggling with the syntax!!
Hello,im having a problem integrating an SQL statement with my program,it works fine when theres a result but throws an error when there isno result,is there anyway in SQL to make up a row if there isnt one that matchesthe query for example in this i could put indicator values in thereturned fields then a simple check to see if its a proper field of myindicator fieldI know ISNULL works with single values but that only works if there isa row returnedDoes anyone know of any SQL syntax for MS SQL that when no row isreturned it makes on up and parses it backThank you in advance for your help!!Ben
I have a simple table on my webpage which shows data from my database. It all worked fine apart from one part. I wanted the select statement to select only NULL values from a column, as these are classed as open queries. Once I have closed the query a 0 or 1 will automatically be posted and will no longer have a NULL value. I have a simple select statement (which I will post on here when I log in with my work computer) and at the end I have a WHERE Column = NULL. I have also tried WHERE column <> 0.0 AND column <>1.0 and that did not work. If I only did WHERE column <> 1.0, i only get the 0.0 results and none of the NULL results, but if I have no WHERE statement I get all the results including the NULL values.
I have a table that contains an identity column. This column is updated in a stored procedure that has a linked trigger that updates another 'backup' table. How can I ensure that the value of the new row added in the table with the identity is passed back to calling client. ?
The value of @@identity is incorrect as it reflects the value in the 'backup table' not the original table. and use select max() on the original table within the stored procedure could be violated by other users attempting the same operation
I have an accounting database which contains data from various years.The frontend is a VB.Net program. At the year end, the program createsnew voucher and transaction tables and creates new stored procedures forthem.I just append the 'new year' at the end and create themie, Vouchers2001, Vouchers2002, Vouchers2003Similarly Transactions2001, Transactions2002.The data for all the years is in the same database.Also, I maintain a table called 'Books' which contains the Years forwhich data is present in the Database. The Structure of the Books tableisBookID BookYear1 20012 20023 20034 2004My Problem is that i need to know the current balance of any ledger forany year. The method to calculate the balance for any year is to startfrom the Minimum year in the Books table and continue upto the requiredyear. The SQL is as follows.DECLARE @iLedgerID AS INT --will be passed as parameterDECLARE @iYear as INT --will be passed as parameterDECLARE @CurrentBalance as MONEYSET @iLedgerID =1DECLARE @MinBook as INTEGERDECLARE @String nVarchar(4000)SELECT @MinBook = Min(BookYear)FROM BooksWHILE @MinBook <= @iYearBEGINSET @String = ' DECLARE @TT Money ' + char(13) +' SELECT @TT = ISNULL( SUM( ISNULL(Debit,0) - ISNULL(Credit,0) ),0 )'+ ' FROM transactions' + CAST(@MinBook AS CHAR(4)) + ' LEFT OUTER JOINdbo.Vouchers' + CAST(@MinBook AS CHAR(4)) + ' ON dbo.Transactions' +CAST(@MinBook AS CHAR(4)) + '.VoucherID' + ' = dbo.Vouchers' +CAST(@MinBook AS CHAR(4)) + '.VoucherID ' +'WHERE (LedgerID = @iLedgerID)'EXEC sp_executesql @String, N'@iLedgerID Int', @iLedgerID */SET @MinBook = @MinBook + 1ENDNow this is just a sample code. It may have a few glitches. My questionisa) Do I have to create a dynamic sql if the name of the database is notknown ahead of time. If No thenb) I need to add the balance of each year to the grand total. How do ireturn a value from a dynamic sql.TIA*** Sent via Developersdex http://www.developersdex.com ***
I am using a sql command to produce outputs having 3 columns Before running the sql I am spooling the output in .xls format But when I open the .xls file (i.e. the spooled file) data of all the 3 columns appear in a single column with blank spaces between them Is there a way by which I can ensure that each output column of the SQL appears in a seperate column in the excel Sheet
I have a date column that formated and i need to group by it, how do it do this? i get this error code:
Msg 8120, Level 16, State 1, Line 2 Column 'o.Initials' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
here is my query: select * from( SELECT CONVERT(VARCHAR(10), AITDate, 110) AS FormatDate , TechInt as Initials , [Drug] ,[Missed PT Notes] ,[Pt Same Name] ,[PT Family] ,[Wrong PT] ,[Wrong Ques. Asked] ,[DAW] ,[Rx/Refills Omitted] ,[Allergy] ,[Wrong Sig] ,[Strength] ,[Wrong PT Address] ,[Quantity] ,[SVQ] ,[Refills] ,[Write Date] ,[Wrong MD/MD Info] ,[Rx Should be Questioned] ,[TSTF],[Non-Link Image] ,[DC Date],[Days Supply] ,[No Call Card] ,[Order Count] ,[Credit Hold Procedure] ,[Routing] ,[Sig Typo] ,[Verse Missing/Wrong] ,[Right Drug Wrong Form] ,[Others] from tblaitinfo pivot (count(ercode) for ercode in ([Drug],[Missed PT Notes],[Pt Same Name],[PT Family],[Wrong PT],[Wrong Ques. Asked],[DAW],[Rx/Refills Omitted],[Allergy],[Wrong Sig],[Strength],[Wrong PT Address],[Quantity],[SVQ],[Refills],[Write Date],[Wrong MD/MD Info],[Rx Should be Questioned],[TSTF],[Non-Link Image],[DC Date],[Days Supply],[No Call Card],[Order Count],[Credit Hold Procedure],[Routing],[Sig Typo],[Verse Missing/Wrong],[Right Drug Wrong Form],[Others])) p )o group by formatdate
Hi, How to return values from stored procedures?? I have a value whose variable would be set thru this sp and it should return this value. How to do this?
I have this assignment where i have a table full of two digit exam scores and I have to write a function that eliminate x number of top values and x number of bottom values and return all the middle values. When the function is called, obviously a number is entered such as 3 and the top 3 and bottom 3 scores are not returned. i.e. SELECT * FROM GetMiddleValues (3);
If anyone has any ideas on how to accomplish this, that would be great.
I am just starting to learn about stored procs and how great they can make my world. I have been able to create a pro that does some data checking and inserts based on the results but what I have not been able to figure out is how would I pass a message from the proc to my Perl script that calls it? If anyone could point me in the right direction on what commands I should be looking into I would appreciate it.
-- If I get used to envying others... Those things about my self I pride will slowly fade away. -Stellvia
I have a query set that returns values as part of a data set, I need a new one to return values from two queries to a single row.
select '1' as thekey, 'Total Picks' as Tot,sum(prod_qty) as picks from exceed.aseld, exceed.csymh where luis_id in ('I','E') and aseld.whse_id = 1 and ( (aseld.batch_id between goal_beg_batch and goal_end_batch and monitor_group = 'YK')
[code]....
is it possible to get the numbers from keys 1 & 2 on the same row in a new query?
Or if it is easier a query that with give me (completed picks/total picks) = a decimal I can feed to the display as a percentage.
I have data that looks like below (columns are Timestamp, Offered, Answered and Delay). I'm looking to exclude returning records that have a value for Delay that are within the top 10% of values of that column. Are there any 2005 tricks where this can be accomplished in a simple statement?
I have a table of product orders. It contains a row for "platform" and Ineed to return how many times each platform is listed in the DBExample data for platform could be:XBOXXBOXXBOXPLAYSTATIONPLAYSTATIONGAMECUBEPLAYSTATIONI'd like the data to be returned asXBOX - 3PLAYSTATION - 3GAMECUBE - 1How would I go about doing this please?
SELECT Facilities=@V_Facilities From UserLoginFacilities where LoginID=(Select LoginID From UserLogin where LoginName=@pStrUserName and Password=@pStrPassword)
If(@V_Facilities=null)
Set @pOutput = @V_Facilities
Return @pOutput;
Else
Set @pOutput = @V_Facilities
Return @pOutput;
GO
Anyone correct this query , I want return the output from this procedure
I need to create a "simple" sql query but have it formatted and then emailed to individuals. I am trying to convert over from Oracle but I am having a hard time getting the query to be formatted the way I want. Here is the select statement I tried to use with no luck with xp_sendmail:
SELECT ALARM ID, TIMESTAMP as TIME, CLASS, RESOURCE, P, L, F, ALARM_MESSAGE FROM ALARM_LOG WHERE ([TIMESTAMP] < GETDATE() - 1) ORDER BY [TIMESTAMP];
Here what the output should look like with the column headers underlined and then the column data (notice the column heading ALARM MESSAGE is on the next line before any data):
ALARM ID TIME CLASS RESOURCE P L F -------------------- ----------- ----- ---------------- - - - ALARM_MESSAGE ------------------------------------------------------------- B3_TEMP_ALM 02-02@11:21 ALARM BUILDING3_TEMP N G G BUILDING 3 TEMPERATURE ALARM, CALL SECURITY.
B5_TEMP_ALM 02-02@11:22 ALARM BUILDING5_TEMP N G G BUILDING 5 TEMPERATURE ALARM, CALL SECURITY.
How can I run the query and have it formatted and emailed out? What is the best way to accomplish this?
I am trying to output data from my sql table to an excel spreadsheet and send it by email which works fine, the problem is he wants the date to be in the format d-mmm-yy, which is easy to format in excel manually, but he do not want to do this manually. I tried to do this when I select the date from the table to spreadsheet, "select convert(char,value_date,106) from table", but this don't get transported to the excel spreadsheet, I get my results on the spread sheet as dd/mm/yy. Can you please help either to set the date on excel forever to be in this format "d-mmm-yy" or to force this output to excel
Hi, i am trying to return two values from SQL 2000 using a single stored procedure. The stored working fine in Query Analyser and returns the two values and two grids in the results window.
My problem is that when i execute the stored procedure using ADO.Net the dataset only has one of the values. e.g TId : 2, where it should read 'TId' : 2, 'ConfigPath': 'C:lah'
Please could anyone shed ligth on this problem?
here the code for the stored procedure:
CREATE PROCEDURE dbo.GetTillInfo ( @TillIdR varchar(50), @Password varchar(50) ) AS
declare @TillId int declare @configpath varchar(150)
IF Exists (SELECT Id FROM Tills WHERE TillRef=@TillId and TillPassword=@Password) BEGIN
set @TillIdR = (SELECT Id FROM Tills WHERE TillRef=@TillId and TillPassword=@Password) select @TillIdR as 'TId'
set @configpath = (SELECT configpath from customer,tills where tills.customerid = customer.id and tills.id = @login) select @configpath as 'ConfigPath' END ELSE BEGIN set @TillIdR = 0 select @TillIdR as 'TId' set @configpath ='' select @configpath as 'ConfigPath' END GO
Sp which inserts inforamtion into a table works fine. The trigger on that table which then inserts information into another table works fine. Only problem is that the SP will not return anything to Visual Basic.. Anyone know how to fix it?
SPbob INsert into b values(1,1,2,2) select 0
(this is a cut up version of the sp just to show about the way it is formated) Please help.
I am having trouble using Output parameters. I have set up an Execute SQL Task to call a Stored Procedure. I am passing an input parameter and indicating 1 global variable for output to retrieve a unique value from the stored procedure call. When I execute the step, it completes successfully but nothing is returned in my output parameter for the unique value??? Below is the call that I use:
EXEC SYS_GENERATE_ID ?
-in the Execute SQL Task I click the Parameters button to set up the input: Status = Parameter1 and the Output Variable Type: Rowset = GUID.
the stored procedure: CREATE PROCEDURE dbo.SYS_GENERATE_ID (@Statusvarchar(20), @GUID uniqueidentifier = NULL OUTPUT) AS BEGIN SET @GUID = NEWID() INSERT INTO dbo.ACTIVITY (GUID, STATUS) VALUES (@GUID, @Status) SET @GUID = convert(varchar(50), @GUID) RETURN @@ERROR END
A table is correctly populated but the GUID value does not make it back to the calling task??? The Global Variable Type under Package Properties has been changed to "Dispatch" and the value is "Not Displayable"??? Any help that is offered will be appreciated GREATLY!!
I've got this sql statement that keeps returning the wrong data. (it's related to a previous post, but is different)
Code: SELECT C.NAME, OL.PART_ID, SL.SHIPPED_QTY FROM CUSTOMER C INNER JOIN USERS U ON C.ID = U.ID INNER JOIN ORDERS O ON C.ID = O.ID INNER JOIN ORDER_LINE OL ON O.ID = OL.ORDER_ID
i have a stored procedure that has parameters. this dataset is used in a crystal report. the parameters are in the sp and will return records if a value is selected. i would like to return records if one parameter or all parameters are selected. there are 3 parameters, date range, receipt, po # if i select a distinct value and leave the others null, or 2 values 1 null etc, i would like to return the records, i am having trouble with the syntax. thank you
my stored procedure performs actions of deletion and insertion. Both the inserted and deleted items are output in temp tables with single column. Is there a way to return the content of these two tables? Is there a way to return a table from the stored procedure?
I need to return row counts for a list of all our users. The problem with the first query is that it doesn’t search for names within the column, it considers a list of email addresses a unique entry. I need to be able to see how many times each email address appears in the database. The second query obviously does that but I don’t want to have to copy and paste 500 usernames. the to_addr_head is a text column if that matters. Thanks!!
SELECT Table1.to_addr_head, COUNT(*) AS "COUNT(*)" FROM Table1 group by Table1.to_addr_head ORDER BY "COUNT(*)" DESC;
select count(*) where Table1.to_addr_head like '%username%'
I'm trying to query an LDAP server from a stored procedure written for the CLR but not getting the expected results.
The code is as follows:
<Microsoft.SqlServer.Server.SqlProcedure()> _ Public Shared Sub LDAP_UserExists(<Out()> ByRef exists As Boolean, ByVal username As SqlString)
Dim adspath As New StringBuilder() adspath.Append(LDAP://[.......]/ou=Members/cn=) adspath.Append(username)
If username.ToString().Length > 0 Then Dim uobject As New DirectoryEntry(adspath.ToString(), "", "", System.DirectoryServices.AuthenticationTypes.Anonymous) If Not (uobject Is Nothing) Then exists = True Else exists = False End If End If
End Sub
The same code works fine from an ASP.NET. If I deploy the code and execute it with
exec LDAP_UserExists 'username'
I receive the error
Error converting data type varchar to bit.
And if I right-click and select "Execute Stored Procedure..." I receive @exists = 1 and Return Value = 0, regardless of the value I pass in as the username parameter.
Given that the same code works correctly on the ASP.NET page I suspect that this error has something to do with the <out()> parameter in the stored procedure declaration.
Can anyone suggest the correct method of performing this query?