Loop Through A Table Which Has Table Metadata
Feb 18, 2015
I am trying to loop through a table which has table metadata and create a:
- 'STORED PROCEDURE'
- This will SELECT all the data in the table and add a hashed column at the end
- Each table has a unique ID
-
Instead of a cursor would there be a set-based approach to achieving this?
METADATA TABLE :
IDTableNameColumnNameHashByteCalculation
111dbo.TableAColA CAST(ISNULL(LEFT(CONVERT(VARCHARColA, 120), 10),'NA') AS varchar) + '|' +
111dbo.TableAColBCAST(ISNULL(LEFT(CONVERT(VARCHAR,ColB, 120), 10),'NA') AS varchar) + '|' +
111dbo.TableAColCISNULL(ColC,'NA') + '|' +
111dbo.TableAColDISNULL(ColD,'NA') + '|' +
222dbo.TableBColAACAST(ISNULL(LEFT(CONVERT(VARCHAR,ColAA, 120), 10),'NA') AS varchar) + '|' +
222dbo.TableBColBBISNULL(ColBB,'NA') + '|' +
222dbo.TableBColCCISNULL(ColCC,'NA') + '|' +
From the above data I want to generate:
SELECT
ColA
,ColB
,ColC
,ColD
, (CAST(ISNULL(LEFT(CONVERT(VARCHARColA, 120), 10),'NA') AS varchar) + '|' +
[Code] ....
View 2 Replies
ADVERTISEMENT
Apr 1, 2014
I am stuck on finding a solution to transpose source data from a system via a metadata look-up table into a destination table. I need a method to transpose/pivot the source data into columns (which are by various data-types). The datatypes for each column are listed in a metadata table.
Source Data Table:
Table Name: Source
SrcID AGE City Date
01 32 London 01-01-2013
02 35 Lagos 02-01-2013
03 36 NY 03-01-2013
Metadata Table:
Table Name:Metadata
MetaID Column_Name Column_type
11 AGE col_integer
22 City col_character
33 Date col_date
Destination table:
The source data to be loaded into the destination table(as shown below):
Table Name: Destination
SrcID MetaID col_int col_char col_date
01 11 32 - -
01 22 - London -
01 33 - - 01-01-2013
02 11 35 - -
02 22 - Lagos -
02 33 - - 02-01-2013
03 11 36 - -
03 22 - NY -
03 33 - - 03-01-2013
View 7 Replies
View Related
Oct 4, 2013
I'd like to figure out how to use the @FieldDescription table below as an intermediate table between the @SourceData and @Stops data.
declare @Stop table (StopId int, UserField varchar(20))
declare @FieldDescription table (Label varchar(10), ColumnName varchar(10))
declare @UpdateSource table (HasPathway varchar(10))
insert into @Stop (StopId, UserField)
values (1, 'Yes')
[code]...
I want to update @Stop.UserField with thevalue from @UpdateSource where @UpdateSource.HasPathway=@Stop.UserField...but I need to use the @FieldDescription table to determine how to map the columns.
View 3 Replies
View Related
May 11, 2007
As title, such as the PK, data type of each column, etc.
Thanks,
Ricky.
View 6 Replies
View Related
Feb 22, 2006
I have a table with RowID(identity). I need to loop though the table using RowID(not using a cursor). Please help me.
Thanks
View 6 Replies
View Related
Jun 21, 2006
SQL table and column metadata
Is there a way to add or update the column or table (using the extended properties) description metadata via T-SQL (from within a stored procedure) or via a program (such as VB.NET using ADO)?
These metadata properties are available via the SSMS interface:
Columns via the Column Properties/Table Designer/Description
Tables via the Table Properties/Extended Properties/[Extended Property Name]
Thanks in advance,
Mark
View 6 Replies
View Related
Jan 4, 2007
Hello,
I want to set up a Foreach loop container to loop through several flat files. I have a connection manager set up for individual flat files. The metadata for the files is all the same. They are fixed width files, and contain sixty five columns.
I didn't see a place in the container properties to configure the metadata of the files. How can a Foreach Loop Container 'know' the metadata of the flat files that I want to loop through?
Thank you for your help!
cdun2
View 10 Replies
View Related
Apr 10, 2015
I am having one store procedure which use to load data from flat file to staging table dynamically.everything is working fine. staging_temp table have single column.all the data stored in that single column below is the sample row.
AB¯ALBERTA ¯93¯AI
AI¯ALBERTA INDIRECT ¯94¯AI
AL¯ALABAMA ¯30¯
after the staging_temp data gets inserted into main table.my probelm is to handle such a file where number of columns are more than the actual table.if you see the sample rows there are 4 column separated by "¯".but actual I am having only 3 columns in my main table.so how can I get only first 3 column from the satging_temp table.output should be like below.
AB¯ALBERTA ¯93
AI¯ALBERTA INDIRECT ¯94
AL¯ALABAMA ¯30
View 45 Replies
View Related
Mar 9, 2008
I have to write some reports for a database I am not familiar with. Is there a query I can use to find a table name if I know the field name?
example: Select table_name from database where field_name = 'my_field'
Mike
View 1 Replies
View Related
Aug 16, 2005
Is there anyone know if a simple SSIS package (moving data from source table to target table) or task can be called repeatedly using a variable that obtains value once a time from a metadata table containing only table names. Basically, I would like to pass in a table variable to the SSIS package or task to start the ETL for different tables. Thanks a lot!
View 12 Replies
View Related
Jun 29, 2012
I wanted to know that when I create a table using SQL Server, does the table metadata like schemaname and catalogname is stored in memory or in hard-disc. I am trying to extract schemaname and catalogname when the database is down or correctly when I have no connection string. I know about sysindexes, systables etc, but i am not able to understand whether it stores the data which is useful to me like catalogname.
sql query to extract the column names from sysindexes?
View 2 Replies
View Related
Apr 9, 2015
I am having one store procedure which use to load data from flat file to staging table dynamically.
Everything is working fine.staging_temp table have single column. All the data stored in that single column. below is the sample row.
AB¯ALBERTA ¯93¯AI
AI¯ALBERTA INDIRECT ¯94¯AI
AL¯ALABAMA ¯30¯
After the staging_temp data gets inserted into main table.my probelm is to handle such a file where number of columns are more than the actual table.
If you see the sample rows there are 4 column separated by "¯".but actual I am having only 3 columns in my main table.so how can I get only first 3 column from the satging_temp table.
Output should be like below.
AB¯ALBERTA ¯93
AI¯ALBERTA INDIRECT ¯94
AL¯ALABAMA ¯30
How to achieve above scenario...
View 1 Replies
View Related
Jan 22, 2012
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.
View 1 Replies
View Related
May 18, 2004
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.
any threads that i can read from or website..
thanx !!
View 3 Replies
View Related
Jun 4, 2008
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
BEGIN TRANSACTION
EXEC pInsertPersonEX SELECT 1, 'Dr.', FirstName, LastName, Suffix, Email, CAST((LEFT(FirstName, 1) + LastName)as varbinary), 31, PrimarySpecialty, 'Student', REPLACE(REPLACE(REPLACE(OffPhone, '(',''),')',''),'-',''), NULL, 0, 0, NULL, Street, NULL, City, 41, Zip,3 FROM _Phy_Greenville
SELECT * FROM Person WHERE PersonOrganizationID = 31
ROLLBACK TRANSACTION
Here is the whole stored procedure
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pInsertPersonEx]
(
@Active bit,
@PersonPrefix varchar(5),
@PersonFirstName varchar(50),
@PersonLastName varchar(50),
@PersonSuffix varchar(20),
@PersonEmail varchar(100),
@PersonPassword varchar(20),
@PersonOrganizationID int,
@PersonDepartment varchar(50),
@PersonTitle varchar(100),
@PersonPhone varchar(10),
@PersonFax varchar(10),
@PersonInfoRequested bit,
@PersonHCTrained bit = NULL,
@PersonHCTrainedDate DateTime = NULL,
@AddressAddress1 varchar(100),
@AddressAddress2 varchar(100),
@AddressCity varchar(100),
@StateId int,
@AddressPostalCode varchar(10),
--@DepartmentID int,
@RoleID int
)
as
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
INSERT INTO tblHospitalsCoordinated
(
intPersonID
,intHospitalID
,dtmCreatedDate
,dtmModifiedDate
,strModifiedBy
)
VALUES
(
@PersonID
,@PersonOrganizationID
,GetDate()
,GetDate()
,''
)
select @PersonID
View 4 Replies
View Related
Feb 20, 2008
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++; }
}
View 1 Replies
View Related
Sep 10, 2012
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,
[Code] ......
View 3 Replies
View Related
Mar 12, 2008
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')
View 7 Replies
View Related
Aug 25, 2015
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.
View 2 Replies
View Related
May 17, 2008
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?
View 4 Replies
View Related
Sep 20, 2013
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.
View 3 Replies
View Related
Feb 6, 2015
I wanted to insert values in columns as explained in below ex.
I am having a table that contains Column1,Column2,Column3,......,Column10.
Inside my for loop, i am getting Column1 value then Column2 then Column3 values and so on till Column10.
My requirement is that on each iteration,I wanted to insert value of Column1 in field Column1, value of Column2 in field Column2 and so on.
View 3 Replies
View Related
Feb 19, 2015
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]
Don’t know if this is at all possible?
View 2 Replies
View Related
Sep 21, 2005
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.
View 4 Replies
View Related
Jul 20, 2005
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.
View 1 Replies
View Related
May 1, 2007
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?
View 9 Replies
View Related
Nov 15, 2015
I have two tables i have to update table2 using table1 without using while loop.
example given below.
Table1
rid
id
amt
firdate
lastdate
1
1
500
[code]....
View 7 Replies
View Related
Jul 31, 2007
Hello,
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.
View 5 Replies
View Related
Jul 6, 2000
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.
The table looks something like this.
inv# SKU
1001 ABC123
1001 DEF456
1001 GHI789
1002 123DEF
1002 456GHI
1002 876HGT
I need the cursor to go through and number each line, something like this.
inv# SKU Line#
1001 ABC123 1
1001 DEF456 2
1001 GHI789 3
1002 123DEF 1
1002 456GHI 2
1002 876HGT 3
Any help is greatly appriciated.
Thanks
View 1 Replies
View Related
Aug 24, 2015
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
[Code] .....
View 9 Replies
View Related
Oct 22, 2015
I have a problem where I want to create a loop in my script to insert 0's into my table.
I have a temp table with a list of company codes.
SELECT CODE FROM ##SENData GROUP BY CODE
This produces the following;
CODE
00C
00D
00K
00M
00Q
00T
00V
00X (there are 110 of these codes)
I want to insert data into a different table in the following format.
+------+------------+-------+---------+
| CODE | Month | Value | Measure |
+------+------------+-------+---------+
| 00C | 01/09/2015 | 0 | HAR-01 |
| 00D | 01/09/2015 | 0 | HAR-01 |
| 00K | 01/09/2015 | 0 | HAR-01 |
| 00M | 01/09/2015 | 0 | HAR-01 |
| 00Q | 01/09/2015 | 0 | HAR-01 |
| 00T | 01/09/2015 | 0 | HAR-01 |
| 00V | 01/09/2015 | 0 | HAR-01 |
| 00X | 01/09/2015 | 0 | HAR-01 |
+------+------------+-------+---------+
The month will be set from a declared variable and the others will just be hard coded.
View 3 Replies
View Related
Jun 19, 2008
Hi all
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.
Bill Shankley
View 4 Replies
View Related
Nov 9, 2006
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
View 1 Replies
View Related