Newbie Question: Adding A Single Value To A List In A Stored Procedure
Apr 20, 2006
I have two tables. UserIds is a collection of users, with UserId as the primary key. Contacts simply maps pairs of users. Think of it like IM, where one user can have multiple contacts.
Contacts
-------------
UserId - int, the UserId of the user who has the contact
ContactUserId - int, the UserId of the contact
I also have a stored procedure named GetConnectedUserIds that returns all the contacts of a given user. It takes a single parameter, @UserId, the UserId of the user whose contacts I want to get. That's pretty simple:
SELECT ContactUserId FROM Contacts WHERE UserId=@UserId.
Now here's where I get over my head. I actually want that stored procedure to return the user's contacts AND the user's own ID. I want the SELECT statement above, but tack on @UserId to the end of it.
How do I do that?
Thanks in advance for any help. Feel free to answer here or to point me to a useful resource.
My task is to add income by taking few variables from webpage. I had take User ID(From database), Field value by selecting it from DropDownBox( Which value is once again taken from database), Income Description, Date, Amount . I had completed this task successfully by binding DropDownBox to database by query string and added income using stored procedure as below.
I need this to be done using only single Stored Procedure for binding Field Value to DropDownBox and for adding income. Plz tell me how to do this? ASPX.CS file protected void Page_Load(object sender, EventArgs e) { SqlConnection con = null;
con = DataBaseConnection.GetConnection(); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter("select PA_IFName from PA_IncomeFields where PA_UID=@PA_UID", con); da.SelectCommand.Parameters.Add("@PA_UID", SqlDbType.Int).Value = (int)Session["PA_UID"]; da.Fill(ds);
Hi... Am working with asp.net with vb for a MusicProject.. In this I have playlist for particular User..ie User Selects Some Songs and clicks on AddToMyPlayList Button.... Here He can insert those songs into a new playlist or update the earlier.. the StroedProcedure is as follws: 'N' means NewPlayList and 'E' means Existing *************************************************************************************** CREATE PROCEDURE MUSIC_ADD_PLAYLIST ( @PLAYLIST_NAME VARCHAR(255), @USER_ID VARCHAR(255), @ItemList NVARCHAR(4000), @delimiter CHAR(1), @FOLDERNAME VARCHAR(255) ,@PLAYLISTTYPE CHAR(1)) AS SET NOCOUNT ON DECLARE @IDENT INT IF @PLAYLISTTYPE = 'N' BEGIN INSERT INTO MUSIC_PLAYLIST ( MUSIC_PLAYLIST_NAME, MUSIC_PLAYLIST_USER ) VALUES ( @PLAYLIST_NAME, @USER_ID ) SELECT @IDENT=@@IDENTITY FROM MUSIC_PLAYLIST END IF @PLAYLISTTYPE='E' BEGIN SELECT @IDENT=MUSIC_PLAYLIST_ID FROM MUSIC_PLAYLIST WHERE MUSIC_PLAYLIST_USER=@USER_ID AND MUSIC_PLAYLIST_NAME=@PLAYLIST_NAME END DECLARE @tempItemList NVARCHAR(4000) SET @tempItemList = @ItemList DECLARE @i INT DECLARE @Item NVARCHAR(4000) SET @tempItemList = REPLACE (@tempItemList, ' ', '') SET @i = CHARINDEX(@delimiter, @tempItemList) WHILE (LEN(@tempItemList) > 0) BEGIN IF @i = 0 SET @Item = @tempItemList ELSE SET @Item = LEFT(@tempItemList, @i - 1) -- INSERT INTO @IDTable(Item) VALUES(@Item) INSERT INTO MUSIC_SONGSLIST (Music_PlayList_Id,Music_SongName,Music_Song_Location) VALUES (@IDENT,@ITEM,@FOLDERNAME+''+@ITEM) IF @i = 0 SET @tempItemList = '' ELSE SET @tempItemList = RIGHT(@tempItemList, LEN(@tempItemList) - @i) SET @i = CHARINDEX(@delimiter, @tempItemList) END GO *************************************************************************************** Here the problem is am not getting the exact result means if i add 6 songs to a playlist it is adding only 4 songs to that particular playlist.. Please help me out Thanks in Advance, Madhavi
Hi All:First of all, I wanna say that I am very new to Stored Procedure, so pardon me for asking questions that seemed like an ABC questions.Alright, so I am creating this login page for my users. They provide their username and pwd. Upon clicking the Login button, some codes were supposed to see if the username exists in the stored procedure. If it is, a welcome message with their username is posted else, an error message will be posted.I've created my stored procedure: (so far, this is what I know)create procedure sp_testing @username varchar(20),@pwd varchar(16) as select userName from testingwhere userName = @userName and password = @pwdYup, I am stuck! Haha. I tried to write some codes on my code-behind, but there's an error or it doesn't work.I hope you all know what I am trying to say. So basically, the inputs are only the username and pwd. But I've been cracking up with these stuffs for three days and still have no luck. Could anyone out there help me?Thanks a lot!
I'm looking to write my first stored procedure. I need to find out the Identity for a record that I just did an INSERT on. I've achieved the proper outcome with a second query, but I'd really like to use a SP here. I think I could use some instance of the @@identity method in SQLServer 7. Can anyone offer some suggestions? Thanks
I am trying to write a stored procedure to do the following below:
The printed check file has a name that looks like this: A111111B222222222C3333333333D50E50.PDF.* In the example name above, 111111 is the check number, 2222222222 is the routing number and 3333333333 is the account number.
The letters define the piece of data that follows.* * ·******** A = Check number ·******** B = Routing number ·******** C = Account number
Steps: a. stored procedure to pull the check number, routing number and account number from tblCheckRegister. b. Join them together in proper format. b. Once it has done that, do a wildcard search on a table called tblSIValidate column SIBarCode. c. The return value should be the entire SIBarCode column.* Append the .PDF to it and look in the same image directory as the cancelled check.
I am used to VB.net and vbscripting and the syntax there. I am sure there are things below in the stored procedure that are not correct. Any help is appreciated.
I have a query that select rows from the employees,salary_head and salary_group tables this is the query SELECT TOP 100 PERCENT dbo.salary_head.salary_group_id, dbo.salary_group.salary_group, dbo.salary_head.amount, dbo.grade_level.[level], dbo.employees.employ_name, dbo.employees.work_id, dbo.employees.company_id, dbo.employees.designation, dbo.salary_head.level_id, dbo.employees.terminate, dbo.employees.banks_id, dbo.employees.bank_account_no FROM dbo.employees INNER JOIN dbo.salary_head INNER JOIN dbo.salary_group ON dbo.salary_head.salary_group_id = dbo.salary_group.salary_group_id ON dbo.employees.level_id = dbo.salary_head.level_id INNER JOIN dbo.grade_level ON dbo.employees.level_id = dbo.grade_level.level_id ORDER BY dbo.grade_level.level_no DESC, dbo.salary_head.salary_group_id i also have a table called payrollers1 with the following fields payroll_id int auto period_id int employee_id level_id designation_id banks_id bankaccount_no salarygroup_id AmountI am trying to write a stored procedure that will run the above query and then insert the values of the employee_id,level_id,designation_id,salary_group_i d,amount rows into the payroller table. As for the period_id i want the Stored procedure to look up the max payperiod_id value in the payperiod table. I am totally new to stored procedure and do not know how to write this code. Can somebody help me with this code.
Hi everybody. I am not sure if I'm even posting in the right forum... I tried my best.
I need to write a stored procedure that'll work with two values, @FromValue and @ToValue.
In Query Analyzer, when this stored procedure is executed with user-given values (@FromValue/@ToValue), I need it to loop until the program reaches the ToValue number.
Lets say I executed the SP with given values @FromValue = 1 and @ToValue = 5, the result should be
1, 2, 3, 4, 5
Listing out all numbers 1 to 5, with a comma and space after each number.
I just created a stored procedure in SQL Server 2005 management studio. I went to my db and expanded the programmability folder then right clicked the stored procedures folder and created a stored procedure. I saved the procedure as sp_getDistance in the default folder SQL managment studio picked. Now when I went back to that stored procedure folder I did not see my stored procedure sp_getDistance, all that was there was the system stored procedure folder. Did I save the stored procedure in the wrong place, or what did I do wrong. I can't find the procedure anywhere, its just sitting in my My DocumentsSQL Server Management StudioProjectssp_getDistance.sql folder. Thanks,Kyle Spitzer
So at the moment, I don't have a function by the name CONCATENATE. What I like to do is to list all those different values that go with a single CASE_ID to appear as a a comma separate list. You might have a better way of doing without even writing a function
calculate age:CREATE PROCEDURE selectage ASSELECT Age = datediff(yy, birthday, getdate()) + case when datepart(dy, birthday) <= datepart(dy, getdate()) then 0 else -1endFROM nopaymy ? is how do fix this problem:I add inWHERE (((Age)>= @age1 And (Age)<= @age2)) and it will complain about Age is not a column, so how would i store the underlined and bold Age aboves value?
Currently I add a new stored procedure in Enterprise Manager by right-clicking Stored Procedure and clicking New Stored Procedure then copy/paste text of procedure into window displayed. Whenever we set up new customer, this process is repeated several times to get all of our stored procedures loaded. Is there a way to automate this process? Thanks
Hi all,I am creating a ASP.Net 2.0 website and in it I had to create a CLR stored procedure to do a complex sql procedure. Coming to the problem I created the CLR stored procedure as a different database project . I wanted to know whether its possible to add the CLR managed code into my exisiting ASP.Net project in which case I should get the dll for this stored procedure in order to deploy the stored proc in the SQL Server.Or is there some simplified approach to using clr stored procedures in an ASP.Net project.
Hi,I just try to add a variable (ORDER BY) to the end of a select statement and it doesn't work. I try so many things but im a newbie in SQL.Help!!!I want to add @OrderBy at the end of :-----------------SELECT *FROM AnnoncesWHERE CategoryID = @CategoryID AND DateOnCreate >= @DateFinale-----------------My declaration :Declare @OrderBy nvarchar(50)If @Sort = 'date_de' set @OrderBy = ' ORDER BY DateOnCreate DESC'Else set @OrderBy = ' ORDER BY DateOnCreate ASC'
I am have stored procedure that accepts one parameter and returns a single value The sp works fine. My question is how do I set the c# webpage to return the single value. I need a specific example of how to code. this is how the code should work. A blank form is loaded, when the user clicks submit I need the code to pull the Login name from the text box and check to see if it exist. I have the sp working the way I need it to. But I can figure how to pull the single value into a variable in the code behind. I am using dataset elsewhere on the site, so I created a ds the calls the sp. Can it work this way? thanks,
I'm trying to build a dynamic sql statement in a stored procedurre and can't get the like statement to work. My problem is with the single quote. for example LIKE '%@searchvalue%'. This works fine: select * from view_searchprinters where serialnumber like '%012%' But I can't figure out how to create this in a stored procedure. What syntax should I use for the line in bold?SET NOCOUNT ON;DECLARE @sn varchar(50)SET @sn = N'012'DECLARE @sql nvarchar(4000)SELECT @sql = 'select top 10 * from view_searchprinters' + ' WHERE 1 = 1 'SELECT @sql = @sql + ' 'IF @sn IS NOT NULL SELECT @sql = @sql + 'and serialnumber LIKE ''' + '%' + '@sn' + '%' + ''' 'EXEC sp_executesql @sql, N'@sn varchar(50)', @sn
I have the following, which loads up a product search i now want to be able to sort it based on criteria such as price. This is what i have so far; String str = Session["subCategoryID"].ToString(); SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["streamConnectionString"].ConnectionString);SqlCommand command = new SqlCommand("stream_CategoryResults", conn); command.Parameters.Add("@subCategoryID", SqlDbType.Int).Value = str;command.CommandType = CommandType.StoredProcedure; conn.Open();SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection); dgProducts.DataSource = reader; dgProducts.DataBind(); conn.Close(); My question is would i need to have different stored procedures, for when loading it up, and when sorting it by price. This is what my stored procedure looks like;CREATE PROCEDURE stream_CategoryResultsByPrice @subCategoryID INT AS SELECT DISTINCT Companies.companyName, Companies.companyLogo,SubCategories.subCategoryName, Products.productPrice, Products.productInfoURL FROM Companies INNER JOIN Products ON Companies.companyID = Products.companyID INNER JOIN SubCategories ON Products.subcategoryID = SubCategories.subCategoryID WHERE SubCategories.subCategoryID=@subCategoryID
Hello, I'd greatly appreciated if someone can help me out on this problem: I'd like to pass a string (which is a multiple value in this case - "Smith", "Lee", "Jones", "Hanson") as an input parameter to a stored procedure. I'd like to use this string as part of the select statement:
exec sp_GetLN "smith, lee, jones, hanson"
In the stored procedure: @strLN varchar <- "smith, lee, jones, hanson"
/*What do I need to do here to SET/REPLACE the original string so that the syntax can be accepted by the select statement??*/
SELECT * from tblCustomers WHERE LASTNAME IN (@strLN)
It looks simple but I've been trying to get the syntax to work. What can I do to change the quote from ' to "?? Can I use char(34) like VB?? Your help is greatly appreciated~
How can I send a list(s) of data into a stored procedure for processing?
For instance, I have a table: GroupContacts(groupname, userid, contactid). At times I will be inserting X amount of records into it, X depends on how many contacts need to be added to a group by a user.
How can I send a list of (groupname, userid, contactid)'s into a stored procedure and then use some kind of for-loop to iterate through the list and insert the records?
I have been converting a VB 6 applications database queries into SQL Server 2000 stored procedures and have come up against a problem where lists are used in search conditions...For example a list of accounts are selected based on their account currency ID being equal to 1, 5, or 7. In the VB 6 query the string looks like....
SELECT tblAccount.txtName FROM tblAccount WHERE (tblAccount.intCurrencyId IN(1, 5, 7))
The list could contain a single value or upto 20 values. Is it possible to pass the currency list (i.e "1, 5, 7, ...") as a parameter to the stored procedure?
I am writing a utility that creates Java code to access a database. I am looking for a way to get a list of fields and types that are returned by an sproc. Is there any easy way to get this from the master? Do you need to parse the SQL? This list would be like what Visual Studio.NET shows, or interdev if I remember correctly.
I need to create a script which iterates over a list of about 40,000 id's. As the list goes through each id other stored procedures are called which do something. Because of access rights on the server im running the script i need to hard code the 40,000 records in my script. The id's are currently in an excel file
What way can i store them in the script, should i use a cursor, and if so how can i create a cursor to hold so many hard coded values
Any help or alternative ideas would be much appreciated
The stored procedure below was working fine and I have added a inner join to it and it stopped working. I have highlighted the new code I have added to the stored procedure in red. Any suggestions on how to solve this issue?
I am getting the below error Server: Msg 209, Level 16, State 1, Procedure AIG_GetRECON_TRANSACTION, Line 53 Ambiguous column name 'REINS_TYPE_CD'.
below is the query i changed.
ALTER PROCEDURE [dbo].[AIG_GetRECON_TRANSACTION] @RECON_TRNSCTN_ID int=NULL, @RECON_ITEM_ID int=NULL, @DIVISION_ID int=NULL, @REINS_TYPE_CD int=NULL, @TRANSACTION_NO char(10)=NULL, @TRANSACTION_NAME varchar(100)=NULL, @REF_NUMBER varchar(20)=NULL, @POLICY_CRS_REF_NO varchar(20)=NULL, @GL_DTFrom datetime=NULL, @GL_DTTo datetime=NULL, @TRANSACTION_CD int=NULL, @AMOUNT money=NULL, @FILE_STATUS_CD int=NULL, @TRNSCTN_OWR_CD int=NULL, @ISSUE_CD int=NULL, @SUPP_ISSUE_CD int=NULL, @IRC_CLASSIFICATION_CD int=NULL, @UNDER_90_DAYS money=NULL, @OVER_90_DAYS money=NULL, @AGING_DAYS_CNT int=NULL, @VOCHER_NO varchar(50)=NULL, @LOADED_DTFrom datetime=NULL, @LOADED_DTTo datetime=NULL, @SPUsageMode TINYINT = 0 -- This should be the last parameter
AS
------------------------------------------------------------------------------- -- SP Usage Audit Info -- DO NOT REMOVE -- All Stored Procedure code MUST be placed between Section 1 and 2 of -- SP Usage Audit code ------------------------------------------------------------------------------- -- SP Usaged Section 1 - Declare ------------------------------------------------------------------------------- DECLARE @SPStartTime DATETIME SELECT @SPStartTime = GETDATE() DECLARE @SPEndTime DATETIME DECLARE @AuditCount INT -------------------------------------------------------------------------------
FROM AIGNET.dbo.RECON_TRANSACTION AS RE INNER JOIN REINSURANCE_TYPE REI ON RE.REINS_TYPE_CD = REI.REINS_TYPE_CD WHERE (@RECON_TRNSCTN_ID IS NULL OR @RECON_TRNSCTN_ID=RE.RECON_TRNSCTN_ID) AND (@RECON_ITEM_ID IS NULL OR @RECON_ITEM_ID=RE.RECON_ITEM_ID) AND (@DIVISION_ID IS NULL OR @DIVISION_ID=RE.DIVISION_ID) AND (@REINS_TYPE_CD IS NULL OR @REINS_TYPE_CD=RE.REINS_TYPE_CD) AND (@TRANSACTION_NO IS NULL OR @TRANSACTION_NO=RE.TRANSACTION_NO) AND (@TRANSACTION_NAME IS NULL OR @TRANSACTION_NAME=RE.TRANSACTION_NAME) AND (@REF_NUMBER IS NULL OR @REF_NUMBER=RE.REF_NUMBER) AND (@POLICY_CRS_REF_NO IS NULL OR @POLICY_CRS_REF_NO=RE.POLICY_CRS_REF_NO) AND ((RE.GL_DT IS NULL) OR (RE.GL_DT BETWEEN @GL_DTFrom AND @GL_DTTo)) AND (@TRANSACTION_CD IS NULL OR @TRANSACTION_CD=RE.TRANSACTION_CD) AND (@AMOUNT IS NULL OR @AMOUNT=RE.AMOUNT) AND (@FILE_STATUS_CD IS NULL OR @FILE_STATUS_CD=RE.FILE_STATUS_CD) AND (@TRNSCTN_OWR_CD IS NULL OR @TRNSCTN_OWR_CD=RE.TRNSCTN_OWR_CD) AND (@ISSUE_CD IS NULL OR @ISSUE_CD=RE.ISSUE_CD) AND (@SUPP_ISSUE_CD IS NULL OR @SUPP_ISSUE_CD=RE.SUPP_ISSUE_CD) AND (@IRC_CLASSIFICATION_CD IS NULL OR @IRC_CLASSIFICATION_CD=RE.IRC_CLASSIFICATION_CD) AND (@UNDER_90_DAYS IS NULL OR @UNDER_90_DAYS=RE.UNDER_90_DAYS) AND (@OVER_90_DAYS IS NULL OR @OVER_90_DAYS=RE.OVER_90_DAYS) AND (@AGING_DAYS_CNT IS NULL OR @AGING_DAYS_CNT=RE.AGING_DAYS_CNT) AND (@VOCHER_NO IS NULL OR @VOCHER_NO=RE.VOCHER_NO) AND ((RE.LOADED_DT IS NULL) OR (RE.LOADED_DT BETWEEN @LOADED_DTFrom AND @LOADED_DTTo))
End
------------------------------------------------------------------------------- -- SP Usage Audit Info -- DO NOT REMOVE -- SP Usage Section 2 - INSERT Audit Info ------------------------------------------------------------------------------- SELECT @AuditCount = @SPUsageMode + (SELECT ParameterFlag FROM DBPerfMon.dbo.SPUsageParameters WITH (NOLOCK) WHERE Parameter = 'SPUsageByPass')
------------------------------------------------------------------------------- -- Absolutely NO Stored Procedure code written beyond this point -------------------------------------------------------------------------------
I'm trying to write a stored procedure that performs a select statement of the RequestID column and the total of the disk size for that row. ie the values on RequestAdditionalDisk1Size + RequestAdditionalDisk2Size + RequestAdditionalDisk3Size where the Requester equals a certain value. I can perform the select statement fine on the individual values, how to add the values of the Disk sizes together and present that back in the select statement.So far the code looks like but is giving me an error around the line performing a SUM.
-- Author:<Author,,Name> -- Create date: <Create Date,,> -- Description:<Description,,> -- ============================================= ALTER PROCEDURE [dbo].[spMyRequests] -- Add the parameters for the stored procedure here
Is there a way to retrieve the parameter list for a given stored procedure?
I am trying to create a program that will autogenerate a list of stored procedures and their parameters so that changes to the database can be accurately reflected in code.
I need to call a stored procedure in order to list products by either a text box based search or by clicking on a category.I am very new to this and would really appreciate any knowledge anyone could share.
I have several tables that are related with the same primary key that I need to make a consolidated list of values for. The schema of each table is similar but some have more or less fields than others. I want to make a list of all table names, field names, and the value of that field. I can select all tables included from sysobjects. The existence of the key is probable but not guaranteed in all tables. The basic table format is: Table1------ID Field1 Field2 Field31 0.0 4.1 3.92 0.5 1.3 0.23 7.1 8.8 9.3 Table2------ID Field10 0.41 3.32 2.73 5.7 Table3------ID Field1 Field22 2.4 4.63 4.3 8.1 Format of the result set:(specifying ID = 2) Table_Name Table_Field ValueTable1 Field1 0.5Table1 Field2 1.3Table1 Field3 0.2Table2 Field1 2.7Table3 Field1 2.4Table3 Field2 4.6
I would like to write a store prodecure to return a month:
My output: Wk1 = July Wk2 = July Wk3 = July Wk4 = July Wk5 = Aug
and so on..
then i create list of array like below:
The counter for insert the week one by one
DECLARE @TotalWeek INT, @counter INT DECLARE @WeekNo varchar, @Month varchar SET @WeekNo = '4,9,14,18,22,27,31,35,40,44,48,53' --this is weekno,if less than 4, month is july, lf less than 9, month is august and so on SET @TotalWeek = 53