i just want to check whether the given data exists in the database. i am using stored procedure. is there any way to know whether that value exists in database without the need to select anything?
I am using VB6 and SQL Server 6.5. I want to pass a boolean to a SQL Server stored procedure. The code below is the main part that tries to pass 'True' to the stored procedure, but an error occurs when the line rst.Open.... is reached ? The error is as follows: The application is using arguments that are of the wrong type, are out of acceptable range, or are in conflict with one another.
I have tried putting 'True' directly in the rst.Open... line instead of assigning it to a boolean variable but the same error occurs.
The stored procedure works fine when run in SQL Server.
Hi all,How do you select and check a boolean value within a stored procedure? I don't know if this is correct or not:DECLARE @CheckStatus bitSELECT @CheckStatus = PREF_STATUS FROM tblPrefsWHERE [PREF_ID] = @PREF_IDIF (@CheckStatus IS FALSE) -- DO SOMETHINGIF (@CheckStatus IS TRUE) -- DO SOMETHING But I'm not sure if what I've used (IS FALSE/TRUE) is the correct way? "PREF_STATUS" is a bit column in my table.Thanks.
Hi,I have a stored procedure (the code is below) that I use to retrieveone value from my database. I tested the code in Query Analyzer, and itworks (I get the value I was looking for). However, when I call thesame code from the stored procedure, I get no value. The code that isexecuted is the same and the input parameter is the same. Does anybodyhave an idea?The code:SELECT Top 1CharID,CharName,CategoryName,CharDescription,UserIDFROM [Character]WHERE CharName='Character'-- returns the right valueThe Stored Procedure:CREATE PROCEDURE SpCharacters_SelectOneByUserName@UserName NVarCharASSELECT Top 1CharID,CharName,CategoryName,CharDescription,UserIDFROM CharacterWHERE CharName=@UserNameGO-- returns no value
Hello,I have a stored procedure: -- Get an individual league match by IDALTER PROCEDURE [dbo].[mb_League_GetLeagueMatchByID]( @LeagueMatchID int)ASSET NOCOUNT ONSELECT * FROM mb_LeagueMatch WHERE mb_LeagueMatch.LeagueMatchID = @LeagueMatchIDThe mb_LeagueMatch table has a column named IsActive that is a bit datatype.The value for all rows is set to true (in database explorer in visual studio 2005).When I execute the above stored procedure I always get -1 (I'm guessing that means null) as a result for IsActive if it was true and 0 when false (as expected).However, when I run a query on the database for the same parameter, I get the expected 1 as the value for IsActive.Has anyone seen this before?Thanks,Howard
Hi, I need to know whether a stored procedure returns only a single record or it can return more than one if the query if for example to return all records in a specific date range. Thanks.
I am new to SQL and SQL Server world. There must be a simple solutionto this, but I'm not seeing it. I am trying to create a crystalreport (v8.5) using a stored procedure from SQL Server (v2000) inorder to report from two databases and to enable parameters.When I create the stored procedure, it joins multiple one-to-manyrelationship tables. This results in repeated/duplicate records. Isthis an issue that should be solved within the stored procedure, or isthis inevitable? If latter, how do you eliminate the duplicates inCrystal Reports?Let's say we have three different tables - Event, Food, Equipment.Each event may have multiple food and multiple equipments; some eventsmay not have food and/or equipments. The stored procedure outcome maylook like this:Event Food Food_Qty EquipmentEquipment_QtyEvent1 Food2 10 Equipment51Event1 Food4 10NULL NULLEvent2 Food4 50 Equipment210Event2 Food4 50 Equipment52Event2 Food1 12 Equipment210Event2 Food1 12 Equipment52As you can see in Event2, for each Food variations, Equipment valuesrepeat. When I am creating a Crystal Reports, I have the duplicationproblem.What I would like to see in the report is either:Event1Food2, 10 Equipment5, 1Food4, 10Event2Food4, 50 Equipment2, 10Food1, 12 Equipment5, 2OR:Event1Food2, 10Food4, 10Equipment5, 1Event2Food4, 50Food1, 12Equipment2, 10Equipment5, 2Attempt1: Using "Eliminate Duplicate Record" option does not work withthe Equipment section since CR does not recognize "Equipment2" in thethird line of the table and "Equipment2" in the fifth line of thetable as duplicates.Event1 Food2, 10 Equipment5, 1Food4, 10Event2 Food4, 50 Equipment2, 10Equipment5, 2Food1, 12 Equipment2, 10(duplication)Equipment5, 2(duplication)Attempt2: I created group for each category (Event, Food, Equipment),put the data in Group Headers and used "Suppress Section" to eliminateif the same equipments are listed more than once within the Foodgroup. This eliminated the duplication, but the items do not aligncorrectly.Event1 Food2, 10 Equipment5, 1Food4, 10Event2 Food4, 50 Equipment2, 10Equipment5, 2Food1, 12 (I want this to appear right below the'Food4, 50' line)I would really appreciate any suggestions! Thank you in advance.
DECLARE @strRole nvarchar(15), @ContactID int SELECT @strRole = Role, @ContactID = ContactID FROM Contact WHERE UserName = @strUserName Select DISTINCT Contact.ContactID ID, UPPER(Surname + 'gd ' + Forename ) AS Description, UPPER(Surname + ' ' + Forename + ' ' + ContactReference) AS Description_CR , UPPER(ISNULL(ContactReference,'')) ContactReference FROM Contact LEFT JOIN AssignedEmployee on Contact.ContactID = AssignedEmployee.ContactID WHERE RUEmployee=1 AND ( ((@CourseID = 0 AND @blnIsSearch=1 ) OR COALESCE(AssignedEmployee.CourseID,0) = @CourseID)) AND (@ProjectID = 0 OR COALESCE(AssignedEmployee.ProjectID,0) = @ProjectID) AND ( (@strRole = 'MIS_TUTOR' AND (AssignedEmployee.ContactID = @ContactID OR CourseID IN (SELECT CourseID FROM AssignedEmployee WHERE ContactID = @ContactID AND Lead = 1) OR AssignedEmployee.ProjectID IN (SELECT ProjectID FROM AssignedEmployee WHERE CourseID IS NULL AND Lead = 1 AND ContactID = @ContactID)) ) OR (@strRole <> 'MIS_TUTOR') ) SET CONCAT_NULL_YIELDS_NULL ON GO
now if i run this stored procedure in Query Analyzer like so...
but if i lift the SQL out of the stored procedure and run it in Query Analyzer like so....
Code Block SET CONCAT_NULL_YIELDS_NULL OFF
DECLARE @ProjectID int, @CourseID int, @blnIsSearch int, @strUserName nvarchar(20) SET @ProjectID = 0 SET @CourseID = 0 SET @blnIsSearch = 1 SET @strUserName = 'K_T'
DECLARE @Role nvarchar(15), @ContactID int SELECT @Role = Role, @ContactID = ContactID FROM Contact WHERE UserName = @strUserName PRINT @ContactID Select DISTINCT Contact.ContactID ID, UPPER(Surname + ' ' + Forename ) AS Description, UPPER(Surname + ' ' + Forename + ' ' + ContactReference) AS Description_CR , UPPER(ISNULL(ContactReference,'')) ContactReference FROM Contact LEFT JOIN AssignedEmployee on Contact.ContactID = AssignedEmployee.ContactID WHERE RUEmployee=1 AND ( ((@CourseID = 0 AND @blnIsSearch=1 ) OR COALESCE(AssignedEmployee.CourseID,0) = @CourseID)) -- the above line was modified to make sure only employees explicitly assigned to a project are brought back. unless it's a search AND (@ProjectID = 0 OR COALESCE(AssignedEmployee.ProjectID,0) = @ProjectID) AND ( (@Role = 'MIS_TUTOR' AND ( (AssignedEmployee.ContactID = @ContactID OR CourseID IN (SELECT CourseID FROM AssignedEmployee WHERE ContactID = @ContactID AND Lead = 1))) OR AssignedEmployee.ProjectID IN (SELECT ProjectID FROM AssignedEmployee WHERE CourseID IS NULL AND Lead = 1 AND ContactID = @ContactID) ) OR (@Role <> 'MIS_TUTOR') )
SET CONCAT_NULL_YIELDS_NULL ON
i only get 5 records returned???
so why do i get a difference when its the same SQL??
Username 'K_T' is of role 'MIS_TUTOR' therefore @Role = 'MIS_TUTOR'
any help on unravelling this mystery is appreciated!
I have a stored procedure on a SQL server, which is workign correctly to check some date/time parameters and then insert a row into a log table. I am calling it from an ASP page. Initially I just called it and didn't worry about the return value. However the Stored procedure now will return a value to determine if it made the change or not and if not why (ie log entry was at incorrect time etc). I woudl liek to capture this returned value in my code to display a message to the user but am havign problems finding the right way to get the value. I am calling the SP as follows: Shared Sub createlogentry(ByVal ID, ByVal tme, ByVal val) Dim result As String Dim cs As String = ConfigurationManager.ConnectionStrings("connecttion1").ToString Using con As New System.Data.SqlClient.SqlConnection(cs) con.Open() Dim cmd As New System.Data.SqlClient.SqlCommand() cmd.Connection = con cmd.CommandType = Data.CommandType.StoredProcedure cmd.CommandText = "CreateLogEntry" cmd.Parameters.Add("@ChID", Data.SqlDbType.Int) cmd.Parameters("@ChID").Value = ID cmd.Parameters.Add("@Value", Data.SqlDbType.Int) cmd.Parameters("@Value").Value = val result = cmd.ExecuteNonQuery().ToString End Using End Sub
I have tried amending the ExecuteNonQuery line to ExecuteReader() Any help appreciated Regards Clive
I have trying to do an insert with a subroutine that calls a stored procedure, but it doesn’ t run. The page loads properly but nothing is inserted in the table of the database, no errors appears after submit the form. <asp:Button id="SubmitButton" OnClick="Send_data" Text="Submit" runat="server"/>
Here is the code:
Sub Send_data(Sender As Object, E As EventArgs)
Dim CmdInsert As New SqlCommand("new_user1", strConnection) CmdInsert.CommandType = CommandType.StoredProcedure
Dim InsertForm As New SqlDataAdapter() InsertForm.InsertCommand = CmdInsert
hi, im new to this site so i don't know if i'm posting in the correct forum. anyway, this is my code:---Dim dbMac As DBLibrary = Nothing dbMac = New DBLibrary(General.GetMACConnectionString)dbMac.OpenConnection("SPR_STAFFMAIN_GETEMPLOYEERECORDS")dbMac.CreateParameter("@USERENTITYID", GetUserEntityID(), Data.SqlDbType.Int)drpEmpNumbers.DataSource = dbMac.GetDataView("StaffMaintenance")gridStaffMaintenance.DataSource = dbMac.GetDataView("StaffMaintenance")gridStaffMaintenance.DataBind()---DBLibrary is a class that opens a connection to the SQL server. i'm getting an empty grid even though the stored procedure returns a row when i test it in the analyzer. is there to debug or test this code? thanks!
could someone please tell me : am I supposed to use the OLE DB Command in a dataflow to call a stored procedure to return a value? Or is it just supposed to be used to call a straightforward insert statement only?
What I am hoping to do:
I have a table with a few columns and one identity column. In a dataflow I would like to effect an insert of a record to this table and retrieve the identity value of the inserted record... and I'd like to store the returned identity in a user variable.
If I AM supposed to be able to do this... then how on earth do I do it?
I have spent hours fooling around with the OLE DB command trying to call a stored proc and get a return value.
In the Advanced Editor any time I try to add an output column (by clicking on Add Column) I just get an error dialog that says "the component does not allow adding columns to this input or output)
So, am getting pretty concussed .. banging my head of the wall like this...
So put me out of my misery someone please.... is the OLE DB Command intended for this or not?
I have a Column called SaleID in some tables in a Database.The SaleID column has the int datatype. I need a stored procedure that returns the next value in sequence for the SaleID column.
For Example, If the last value inserted into the SaleID column was 1022 the stored procedure should return 1023 If the last value inserted into the SaleID column was 1023 the stored procedure should return 1024. If the last value inserted into the SaleID column was 1024 the stored procedure should return 1025.
Also an exclusive lock should be maintained while the the stored procedure is running.
I have a Gridview bound to a SQLDataSource that uses a Stored Procedure expecting 1 or 2 parameters. The parameters are bound to textbox controls. The SP looks up a person by name, the textboxes are Last Name, First Name. It will handle last name only (ie. pass @ln ='Jones' and @fn=null and you get all the people with last name=Jones. I tested the SP in Management Studio and it works as expected. When I enter a last name in the Last Name textbox and no First Name I get no results. If I enter a Last Name AND First Name I get results. I don't understand. Here's the HTML View of the page. The only code is to bind the Gridview when the Search button is pressed. <%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server" TabIndex=1></asp:TextBox> <asp:TextBox ID="TextBox2" runat="server" TabIndex=2></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Search" TabIndex=3 /> <hr /> </div> <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" DataSourceID="SqlDataSource1" DataKeyNames="EmpID" CellPadding="4" EnableSortingAndPagingCallbacks="True" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False"> <Columns> <asp:BoundField DataField="EmpID" HeaderText="Emp ID" ReadOnly="True" SortExpression="EmpID" /> <asp:BoundField DataField="FullName" HeaderText="Full Name" SortExpression="FullName" /> <asp:BoundField DataField="Nickname" HeaderText="Nickname" ReadOnly="True" SortExpression="Nickname" /> <asp:BoundField DataField="BGS2" HeaderText="BGS2" SortExpression="BGS2" /> <asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" /> <asp:BoundField DataField="email" HeaderText="Email" SortExpression="email" /> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:EmpbaseConnectionString %>" SelectCommand="GetByName" SelectCommandType="StoredProcedure"> <SelectParameters> <asp:ControlParameter ControlID="TextBox2" Name="fn" PropertyName="Text" Type="String" ConvertEmptyStringToNull=true/> <asp:ControlParameter ControlID="TextBox1" Name="ln" PropertyName="Text" Type="String" ConvertEmptyStringToNull=true/> </SelectParameters> </asp:SqlDataSource> </form> </body></html>
Ok well i have a stored procedure that returns an integer between 1 and 5. My problem now is i want to check to see if the table will return NULL and if so i don't want to assign the value to my variable otherwise it'll trow an error. My code is listed below but i keep getting the error "Conversion from type 'DBNull' to type 'Integer' is not valid." i've also tried If getoptionpicked.Parameters("@optionpicked").Value = Nothing ThenIf getoptionpicked.Parameters("@optionpicked").Value Is system.dbnull Then below is the rest of the code If getoptionpicked.Parameters("@optionpicked").Value Is Nothing Then Else optionpicked = getoptionpicked.Parameters("@optionpicked").Value If optionpicked = 1 Then option1.Checked = True ElseIf optionpicked = 2 Then option2.Checked = True ElseIf optionpicked = 3 Then option3.Checked = True ElseIf optionpicked = 4 Then option4.Checked = True ElseIf optionpicked = 5 Then option5.Checked = True Else End If End If
I'm pretty new to .NET and am looking for advice on how to speed up a simple stored procedure that returns 35,000 plus rows. It's a super simple query that returns a client list. It's just that there is soooooo many rows, it's super slow when the page loads.
I have a stored procedure that works when executed in query analyzer. (It is also way too long to post here) When called from my application ado.net returns the error:
Invalid object name #idTable
If I run the proc in query analyzer using the same parameters (copied from quickwatch while debugging) there is no error.
While very complicated, this procedure runs quickly so timing out is not an issue.
Does anyone know why a proc would run in query analyzer and not in an asp.net/c# application?
I have a stored procedure like "select * from ThisTable" I'm doing a dataread like: Dim val as String = dateRead("column_from_ThisTable") If the value in the column is not null everything works great, but if the value is null, instead of getting a value of "" which I expect, I get the column name??? In this case "column_from_ThisTable" How do I make sure I get "" returned when the value in the column is db.null?
AS DECLARE@UPLIDCount int DECLARE @OldUPLIDCount int SELECT @UPLIDCount = (SELECT Count(UPLID)/1000 AS adjcount FROM tblProvLicSpecloc WHERE DelDate is null OR DelDate > GETDATE())
IF EXISTS(SELECT var FROM tblDMaxVars WHERE var = 'UPLID Count') BEGIN SELECT @OldUPLIDCount = (SELECT var FROM tblDMaxVars WHERE var = 'UPLID Count') IF @UPLIDCount > @OldUPLIDCount BEGIN UPDATE tblDMaxVars SET value = '' + CAST((@UPLIDCount*1000) AS nvarchar(1000)) + '' WHERE var = 'UPLID Count' END END ELSE BEGIN INSERT INTO tblDMaxVars (var, value, description) VALUES ('UPLID Count', '' + CAST((@UPLIDCount*1000) AS nvarchar(1000)) + '', 'counts UPLID records and rounds down to the nearest thousand') END
GO
The table tblDMaxVars only has three columns, none of which are integers, yet I still return this error:
Code:
Syntax error converting the varchar value 'UPLID Count' to a column of data type int.
Hi there everyone. I have a stored procedure called “PagingTable� that I use for performing searches and specifying how many results to show per ‘page’ and which page I want to see. This allows me to do my paging on the server-side (the database tier) and only the results that actually get shown on the webpage fly across from my database server to my web server. The code might look something like this:
The problem is the stored procedure actually returns two result sets. The first result set contains information regarding the total number of results founds, the number of pages and the current page. The second result set contains the data to be shown (the columns specified). In ‘classic’ ASP I did this like this.
'Open the recordset rsItems.Open strSQL, conn, 0, 1
'Get the values required for drawing the paging table intCurrentPage = rsItems.Fields("CurrentPage").Value intTotalPages = rsItems.Fields("TotalPages").Value intTotalRows = rsItems.Fields("TotalRows").Value
'Advance to the next recordset Set rsItems = rsItems.NextRecordset
I am trying to do this now in ASP.NET 2.0 using the datasource control and the repeater control. Any idea how I can accomplish two things:
A) Bind the repeater control to the second resultset B) Build a “pager� of some sort using the values from the first resultset
com.microsoft.sqlserver.jdbc.SQLServer Exception: A server cursor cannot be opened on the given statement or statements . Use a default result set or client cursor.
If a SP doesnt have a temp table, then there is no issue, SP executes perfectly, but if a SP has a temp table, this error occurs.
SP :
create proc testProcedure @countrCode varchar(3) as
select countryname INTO #TMPCOU from country where countryCode = @countrCode SELECT COUNTRYNAME FROM #TMPCOU
I am databinding a dataset formed from a stored procedure,(all done on page_load). However, the reference to the column name is not recognised with the following error being returned. Column with name "CalcVal" was not found. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException: Column with name "CalcVal" was not found.Source Error:
Line 152: chartCommand.Fill(chartDs); Line 153: Chart1.DataSource = chartDs; Line 154: Chart1.DataBind(); Line 155: Line 156: } This worked before deployment and the other controls which are bound to data using stored procedures seem to work. However, these other data sources are all sqlDatasoure controls. Any suggestions would be helpful. I have found issues relating the to user ID and password which seems to depend on whether the web server and data server are the same machine or whether they are remote from each other. cheers-jim.
SQL (using 2012) .I'm trying to create some stored procedures that calculate stats needed for item response theory and test scoring (things like reliability, correlation, etc.). I'm writing a procedure that's aimed at splitting a test in half (first half of the items and second half of the items) and calculating each individual (TestID) score for each half. I can insert the first half of the test, but end up getting an error stating that the subquery returned more than one value. I know it's being caused by the group by clause, but if I remove it I end up with a total count of the items answered correctly, but it's necessary for me to link it batch to the TestID (so each row should have a BatchID [same for all at the moment], a unique TestId, a corresponding FirstHalfScore and a corresponding SecondHalfScore for each testID).
Insert into SplitHalfTestScores (BatchId, TestID, FirstHalfScore) (Select distinct 10001 as BatchId, irt.TestID, count(*) as FirstHalfScore From irt_TestItems irt where batchID=10001 and ItemId <=40 and TestId = irt.TestId and AnsweredCorrectly = 1 group by TestId)
Update SplitHalfTestScores Set SecondHalfScore = (Select count(*) From irt_TestItems irt where BatchId = 10001 and TestId = irt.TestId and irt.ItemId > 40 and AnsweredCorrectly = 1 group by TestId)
Question:What would be the best way to add carrage returns to a record, and would mymethod create alot of overhead and wasted space. What would be the bestmethod to minimize overhead and wasted space.Scenario:Server MS SQL 2000Table name= mitTicketsFields= problem,details, created, lupdateCurrent Text in record [Data Example for mitTickets.Details]Backup failed. Backup failure investigated and found tape ejected.I would like to create a stored procedure that will append the current Dateand Time to each update that is being submitted via a web form. I only wantthe web form to add text and have the stored procedure append the input textthe the existing record so that the data looks like the following.10/4/2003 9:10:32 AMTape inserted, backup completed successfully.10/4/2003 7:15:02 AMBackup failure investigated and found tape ejected.10/4/2003 6:27:08 AMBackup failed.
Hi all - I'm trying to optimized my stored procedures to be a bit easier to maintain, and am sure this is possible, not am very unclear on the syntax to doing this correctly. For example, I have a simple stored procedure that takes a string as a parameter, and returns its resolved index that corresponds to a record in my database. ie exec dbo.DeriveStatusID 'Created' returns an int value as 1 (performed by "SELECT statusID FROM statusList WHERE statusName= 'Created') but I also have a second stored procedure that needs to make reference to this procedure first, in order to resolve an id - ie: exec dbo.AddProduct_Insert 'widget1' which currently performs:SET @statusID = (SELECT statusID FROM statusList WHERE statusName='Created')INSERT INTO Products (productname, statusID) VALUES (''widget1', @statusID) I want to simply the insert to perform (in one sproc): SET @statusID = EXEC deriveStatusID ('Created')INSERT INTO Products (productname, statusID) VALUES (''widget1', @statusID) This works fine if I call this stored procedure in code first, then pass it to the second stored procedure, but NOT if it is reference in the second stored procedure directly (I end up with an empty value for @statusID in this example). My actual "Insert" stored procedures are far more complicated, but I am working towards lightening the business logic in my application ( it shouldn't have to pre-vet the data prior to executing a valid insert). Hopefully this makes some sense - it doesn't seem right to me that this is impossible, and am fairly sure I'm just missing some simple syntax - can anyone assist?
I was comparing the parameters for two stored procs that I made using the SQL Server 2005 express management studio. Both of these sprocs only inserted one field into a single table. These were both of the type varchar.
One of the sprocs had "nocount on" and the other did not. I thought I would see the returns integer parameter in the sproc that did not have "nocount" set to on. I thought this is what returns an integer to validate an insert. Obviously, I am confused about how this works.
Can anyone help me to understand that difference between nocount on and the parameter that returns an integer.