I have a table that stores a couple of tablenames in the same db.The tablenames in the table can change from time to time.Is it possible to loop through the tablenames in the table and run a query against each table name. I cannot hard code the table names in the query because they can change from time to time.
Is there a way to loop using a cursor in SQL-server so i can see if each columns of each tables that i loop through my DB have a specific string value and change it to something else, renaming the column if the match if correct.
I have a table called _phy_greenville. Its a table that was imported from an excel file. I need to take the values in this table, and pass them to the following stored procedure. This stored proc create the physician record correctly for me when doing one record at a time. What I need to do is pass ALL record in this table (_phy_greenville) into this stored proc. Is there anyway I can loop through, or do some sort of bulk insert?
I tried the following, but obviously this does not work
IF @PersonHCTrainedDate = '01/05/1900' SET @PersonHCTrainedDate = NULL
set nocount on
declare @PersonId int, @AddressTypeID int
insertPerson ( Active, PersonPrefix, PersonFirstName, PersonLastName, PersonSuffix, PersonEmail, PersonPassword, PersonOrganizationID, PersonDepartment, PersonRegistrationDate, PersonLicenseAgreement, PersonTitle, PersonPhone, PersonFax, PersonInfoRequested, PersonHCTrained, PersonHCTrainedDate ) values ( @Active, @PersonPrefix, @PersonFirstName, @PersonLastName, @PersonSuffix, @PersonEmail, convert(varbinary,@PersonPassword), @PersonOrganizationID, @PersonDepartment, getdate(), 0,/* TODO need to get this from form */ @PersonTitle, @PersonPhone, @PersonFax, @PersonInfoRequested, @PersonHCTrained, @PersonHCTrainedDate )
set @PersonID = IDENT_CURRENT('Person')
/* look up the default address type */ select@AddressTypeID = AddressTypeID fromAddressType whereAddressTypeDisplayName = 'Work'
execpInsertPersonAddress @AddressAddress1, @AddressAddress2, @AddressCity, @AddressPostalCode, @StateID, @PersonID, @AddressTypeID, 1/* this proc always inserts the default address */
/* - Schema change. Department now a varchar execpInsertPersonDepartment @PersonID, @DepartmentID, 1/* this proc always inserts the default department */ */ execpInsertPersonRole @PersonID, @RoleID
I have a table of CategoryIDs and I want to increment through it passing each categoryID as a parameter to a stored procedure that returns the TOP 1 row, and build a new table from the the result. I do not know how to pass the categoryID into the stored procedure. I do not know how to begin building the new table. public DataTable GetContractorCats() { // Generates table of all Contractor Category IDs no parameters SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings ["ConnectionString2"].ConnectionString); SqlCommand cmd = new SqlCommand("GetContractorCatIDs", con); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = cmd; DataSet ds = new DataSet(); try { da.Fill(ds, "ContractorCats"); return ds.Tables["ContractorCats"]; } catch { throw new ApplicationException("Data error"); } }protected void Top1EachCategory(){ // need to build a new table row by row using a stored procedure that finds the top result from a database query int RowIncrement; RowIncrement = 0; DataTable dt1 = GetContractorCats(); foreach (DataRow row in dt1.Rows) { I need to pass value of dt1 table ["CG_ID"] as a parameter to Stored Procedure called "GetTop1" Run the stored procedure which returns a single row if the CG_ID is found and use its field values to build each row in a new table. The stored procedure returns C_Name, Category_Name, C_Email, C_RCode and C_City RowIncrement++; }
I have a table with AmountSold and AmountLeftWith. I have to buy from the customers until the amount bought =250,000.
The max that user can buy is 250,000 so customers 1-3 get left with 0 (AmountLeftWith ) and customer 4 with 577 (AmountLeftWith ) after the update as user couldn't buy the entire amount as it would have exceeded 250,000. Preferably the query should stop afterwards and not proceed to check the other customers.
--===== If the test table already exists, drop it IF OBJECT_ID('TempDB..#tmpCustomerAmount','U') IS NOT NULL DROP TABLE #tmpCustomerAmount CREATE TABLE #tmpCustomerAmount ( [id] [int] IDENTITY(1,1) NOT NULL,
I'd like to loop through a database and get all the user table names and insert them into another table. What's the best way to do this without using a cursor? This gives me the last table only.
declare @table_name char(50)
select @table_name = object_name(id) from sysindexes where indid =0
INSERT INTO holding.dbo.tbl_inputfiles (IP_File, IP_Act, IP_Import) Values (@table_name,'Y','ADV')
I was writing a query to get the age and the retirement year for all the employees.And thought of using while loop so that I don't have to write IF conditions or case statements for all the ages.
I'm using the AdventureWorks2012 database.And the actual table looks like this.
SELECT * FROM HumanResources.Employee
*NOTE:- These tables are not the complete tables.
BusinessEntityID JobTitle BirthDate MaritalStatus Gender 1 Chief Executive Officer 1963-03-02 S M 2 Vice President of Engineering 1965-09-01 S F 3 Engineering Manager 1968-12-13 M M 4 Senior Tool Designer 1969-01-23 S M
[Code] ...
And after I wrote the query to get the age and the retirement year of all the employees I got 70 tables for all the ages from 30 to 70. As the starting age is 30 and the last age is 70 in the table.So,I just want to know how I can settle all the tables into a single table as a sinle result and not as multiple results.
The query for age and retirement year....
DECLARE @Counter INT DECLARE @Duration INT DECLARE @Result DATE SET @Counter=(SELECT MIN(DATEDIFF(YY,BirthDate,GETDATE()))FROM HumanResources.Employee) SET @Duration=30
[Code] .....
And the result tables.
BusinessEntityID JobTitle BirthDate AGE MaritalStatus Gender Retirement Year69 Production Technician - WC60 1985-05-07 30 S M 2045-08-25 22:36:38.160115 Production Technician - WC50 1985-07-01 30 S F 2045-08-25 22:36:38.160133 Production Technician - WC40 1985-02-04 30 S M 2045-08-25 22:36:38.160144
[Code] ....
And it goes like this for 70 times. So just want to know how I can merge those 70 tables into a single table.
Hi, how do I loop through a table in a store procedure? I need to check the all the record in a table and do some logic and then insert or update another table base on the logic?
I want to make a SP to update table Product with information I get from table Orderdetail.
Create Procedure UpdateVoorraad §OrderId (int) As Select ProductId, Tal From Orderdetail where OrderId = @OrderId
-- this query get info from table orderdetail : ProductId (integer) and Tal (smallint)
-- Tal = Number of Products
-- Here I want to loop through the query above
-- and for each record in the query I want to update
-- table Product.
Update Product Set Product.Voorraad = Product.Voorraad - Tal where ProductId = ProductId
To do this must I make a create a tempory table, store the query result in the table loop through the table and update table product, or can I try to create a function without a temporary table.
I want to, for each month of the year 2014 say, to create a loop that will enter data into a table.
Right now I have:
Select [Member Number], sum(case when [Receipt Date]='2014/01/01' then Amount else 0 end) as [Rec 2014/01/01] From [Receipts Table] Group by [Member Number] Insert into [Receipts 2014/01/01]
[Code] ....
Instead I would just like to do something like…
Declare i date For i=2014/01/01 to 2014/12/01
Select [Member Number], sum(case when [Receipt Date]=i then Amount else 0 end) as [Rec +i]
From [Receipts Table] Group by [Member Number] Insert into [Receipts + i]
Hi. It seems to be very simple, actually, but I don't know if it isfeasible in TSQL. I have a sproc which gathers in one place many callsto different other sprocs, all of them taking a 'StoreGroupe'parameter. I would like to add a case where if the call has NOStoreGroupe parameter, the sproc should LOOP thru all records in tableStoreGroupeTable, read the column StoreCode, and pass that value as aparam to the other sprocs, as in:CREATE PROCEDURE MySproc(@StoreGroupe nvarchar(6) = NULL)ASif (@StoreGroupe is not null)BeginExec _Sproc1 @StoreGroupeExec _Sproc2 @StoreGroupeExec _Sproc3 @StoreGroupeExec _Sproc4 @StoreGroupe...............EndElseBeginA 'Group Code' has NOT been specifiedI want to take all the StoreGroups in tableStoreGroupeTable, in turn.I would like to do SOMETHING LIKE THIS:Do While not [StoreGroupeTable].EOFRead [Code] from [StoreGroupeTable]Set @StoreGroupe = The value I just readExec _Sproc1 @StoreGroupeExec _Sproc2 @StoreGroupeExec _Sproc3 @StoreGroupeExec _Sproc4 @StoreGroupe...............LoopEndGOIs that feasible in a sproc, or do I have to do this in the client(ADO) ?Thanks a lot.Alex.
Hello,Does anyone know of a way to loop thru a SQL table using code in a storedprocedure?I need to go thru each record in a small table and build a string usingvalues from the fields associated with a part number, and I can't find anyway to process each record individually. The string needs to be initializedwith the data associated with the 1st record's part number, and I need tobuild the string until a new part number is incurred. Once a new part numberis found in the table, the string is written to a different table and resetfor this next part number in the table. Need to repeat until all records inthe table have been processed.I use ADO in access 2000 to work thru local recordsets, I just can't findanyway to do this in a stored SQL procedure.Thanks for any suggestions, Eric.
I would like to loop through a SQL Server table that contains the paths to all the reports we need to run and then execute the reports via SSIS. What task should I be doing to do this? Will the For Loop work for something like this?
Anyone have any suggestions on creating a query that will randomly select records from a table, but not use those records again. I have some code that does it, but it uses the same fields over again, and also throws in some blank records that I did not specify in the query. I am creating a test engine that has to randomly ask questions.
I am importing a text file that list invoice columns. The invoice detail table needs the line items to be listed with sequential numbers. I import the file to a temp table to do the work in and I know I need to have the cursor do loop through and count, however, I have no more hair to pull out.
I'm migrating electronic records from a legacy system and the new system has strict requirements for ASCII characters in certain metadata fields. I wrote a UDF to display illegal characters, so I can work out how to map them.
The UDF used a while loop and to improve performance, I wrote the equivalent UDF using a tally table. The tally table version actually ran significantly slower. Query calling UDF using cross apply took 26 secsfor the while loop versus 119 secs for Tally table, for test data of 97000 rows
I would like to work out why, as I will use similar code to replace the illegal characters .
-- while loop version of UDF
CREATE FUNCTION [dbo].[DisplayIllegalChars](@strText VARCHAR(4000)) RETURNS @TableVariable TABLE ( Chr CHAR(1) ,AsciiValue INT) AS BEGIN DECLARE @intCount INT DECLARE @chrCheck CHAR
I'm new to sql and could do with some help resolving this issue.
My problem is as follows,
I have two tables a BomHeaders table and a BomComponents table which consists of all the components of the boms in the BomHeaders table.
The structure of BOMs means that BOMs reference BOMs within themselves and can potentially go down many levels:
In a simple form it would look like this:
LevelRef: BomA
1component A 1component B 1Bom D 1component C
What i would like to do is potentially create a temporary table which uses the BomReference as a parameter and will loop through the records and bring me back every component from every level
Which would in its simplest form look something like this
LevelRef: BomA
1......component A 1......component B 1......Bom D 2.........Component A 2.........Component C 2.........Bom C 3............Component F 3............Component Z 1......component C
I would like to report against this table on a regular basis for specific BomReferences and although I know some basic SQL this is a little more than at this point in time i'm capable of so any help or advice on the best method of tackling this problem would be greatly appreciated.
also i've created a bit of a diagram just in case my ideas weren't conveyed accurately.
I have a table in SQL, that I know how to connect to using ADO, but Ineed help on how to read records from that table.So on a form I have a listbox where I want to populate that and i havea textbox with a userid.Here is an example of the table:USER ID TYPE PAYMENT=====================0001 CARD 150.000001 CASH 250.000002 CASH 175.00If I have 0001 in the txtuserid textbox, I then want to display inthe listbox:CARD 150.00CASH 250.00How would I do this?thanks
i would like to loop through the table and concatenate the pocket filed for all the records that has the same pk. and insert the pk and the concatenated string into another table in a timely manner.
Here is the steps I should take... 1- Check for the log table and find run status ( there is a date field which tells the day run) 2- Lets say last day was 2008-05-15, So I have to check A1.DDDDMMYYY file exists in the folder for each day like A1.20080516,A1.20080517 and A1.20060518 ( until today) 3- if A1.20080516 text file exist then I have to move it to the table and same thing for other dates like if A1.20080517 exists I have to load it to table and so on
it looks like for each loop, first I have to get the last date and then I have to check the file exists for each date and if the date file exists then I have to load it into table...
Please tell me How can I do it. it looks complex looping...
I am using P_PART_CLS_ATTR as input where I can insert the data as attr_name and attr_value. I want to access each row of inserted values like row by row. I need take attribute name and value process them and return for inserting.. How to access the values in row by row?
Loop through #Temp_1 -Execute Sproc_ABC passing in #Temp_1.Field_TUV as parameter -Store result set of Sproc_ABC into #Temp_2 -Update #Temp_1 SET #Temp_1.Field_XYZ= #Temp_2.Field_XYZ End Loop
It appears scary from a performance standpoint, but I'm not sure there's a way around it. I have little experience with loops and cursors in SQL. What would such code look like? And is there a preferable way (assuming I have to call Sproc_ABC using Field_TUV to get the new value for Field_XYZ?
I want to take the contents from a table of appointments and insert theappointments for any given month into a temp table where all theappointments for each day are inserted into a single row with a columnfor each day of the month.Is there a simple way to do this?I have a recordset that looks like:SELECTa.Date,a.Client --contents: Joe, Frank, Fred, Pete, OscarFROMdbo.tblAppointments aWHEREa.date between ...(first and last day of the selected month)What I want to do is to create a temp table that has 31 columnsto hold appointments and insert into each column any appointments forthe date...CREATE TABLE #Appointments (id int identity, Day1 nvarchar(500), Day2nvarchar(500), Day3 nvarchar(500), etc...)Then loop through the recordset above to insert into Day1, Day 2, Day3,etc. all the appointments for that day, with multiple appointmentsseparated by a comma.INSERT INTO#Appointments(Day1)SELECTa.ClientFROMdbo.tblAppointments aWHEREa.date = (...first day of the month)(LOOP to Day31)The results would look likeDay1 Day2 Day3 ...Row1 Joe, PeteFrank,FredMaybe there's an even better way to handle this sort of situation?Thanks,lq
I have a SSIS package that imports data into a staging table from an excel sheet (This works fine). From the staging tabler i want it to insert the values into my members table, take that unique indentityID that gets created and insert the other values into other tables for that member that was just created.
In the staging table, i have all the values for a single member. But the structure of the database needs all the values inserted into seperate tables. There is no conditions ID in my members table, so the member first has to be created and from there i need to use the newly created member's MemberID and insert the conditions into a seperate table using the MemberID
I have created some sample data that can be used. I think i have an idea of how to do it, but i'm not totally sure if it will work that way, i have however included it in the sample data.
Code Snippet DECLARE @ImportedStagingData TABLE ( ID INT IDENTITY(1,1), Name VARCHAR(50), Surname VARCHAR(50), Email VARCHAR(50), [Chronic Heart Failure] INT, [Colon Cancer] INT ) INSERT INTO @ImportedStagingData VALUES ('Carel', 'Greaves', 'CarelG@Email.com', 1,0) INSERT INTO @ImportedStagingData VALUES ('Jamie', 'Jameson', 'JamieJ@Email.com', 1,1) INSERT INTO @ImportedStagingData VALUES ('Sarah', 'Bolls', 'SarahB@Email.com', 0,1) INSERT INTO @ImportedStagingData VALUES ('Bells', 'Scotch', 'BellsS@Email.com', 1,1) INSERT INTO @ImportedStagingData VALUES ('Stroh', 'Rum', 'StrohR@Email.com', 0,0) DECLARE @Conditions TABLE ( ID INT IDENTITY(1,1), Condition VARCHAR(50) ) INSERT INTO @Conditions VALUES ('Chronic Heart Failure') INSERT INTO @Conditions VALUES ('Colon Cancer') DECLARE @Members TABLE ( MemberID INT IDENTITY(1,1), Name VARCHAR(50), Surname VARCHAR(50), Email VARCHAR(50) ) DECLARE @memConditions TABLE ( MemberID INT, ConditionID INT ) SELECT * FROM @ImportedStagingData SELECT * FROM @Conditions SELECT * FROM @Members SELECT * FROM @memConditions /* --- This is the part that i am battling with --- DECLARE @CurrentValue INT DECLARE @numValues INT SET @numValues = (SELECT COUNT(ID) FROM @ImportedStagingData) WHILE @numValues <> 0 BEGIN INSERT INTO @Members SELECT Name, surname, email FROM @ImportedStagingData GO SET @CurrentValue = (SELECT IDENT_CURRENT('@ImportedStagingData')) INSERT INTO @memConditions (MemberID), (ConditionID) VALUES (@CurrentValue, --ConditionValue from @ImportedStagingData, all the values that have a 1)