Dynamically Access A Column In A Table

May 21, 1999

I'm trying to create a procedure that can access a column in a table dynamically.<br>
Lets say I have the following table<br>
create table table_items<br>
(rec int identity not null,<br>
item1 int,<br>
item2 int,<br>
item3 int)<br>

and I have a procedure as such

create procedure access_item<br>
@rec int,<br>
@itemindex int,<br>
@item int as<br>
select @item = (select item1 from table_items where rec = @rec)<br>

However, the column I want to access is @itemindex.<br>
If @itemindex = 1, then set @item to item1<br>
if @itemindex = 2, then set @item to item2<br>
if @itemindex = 3, then set @item to item3<br>

I can't use a simple 'if/then' selection, because the number of columns in the table can grow, and I don't want to have to rewrite the procedure everytime a column is added.<br>
How do I do this?<br>

I tried to use an execute command, as such<br>

create procedure access_item_2<br>
@rec int,<br>
@itemindex int,<br>
@item int as<br>
declare @sql varchar(255)<br>
select @sql = "select @item = (select item" + convert(varchar(2), itemindex) + " from table_items where rec = @rec)"<br>
execute (@sql)<br>

but when the procedure runs, I get the following error:<br>
'@item is not a valid variable.'<br>

What else can I do?<br>

Please e-mail me at sam@microcsl

View 2 Replies


ADVERTISEMENT

Create Table And Column Dynamically

Jun 2, 2008

Hi,
There is a table exists in a database, I have to write a stored procedure to create the same table in different database, with the same column name and field. This should be done in runtime. Is it possible. The table will be passed as a parameter to the stored procedure.

View 3 Replies View Related

Adding A Column To A Table Dynamically Against A Database?

Oct 3, 2007

I have the folowing databases DB1,DB2,DB3,D4,DB5........
I have to loop through each of the databases and find out if the database has a tablename with the word 'Documents'( like 'tbdocuments' or 'tbemployeedocuments' and so on......)
If the tablename having the word 'Documents' is found in that database i have to add a column named 'IsValid varchar(100)' against that table in  that database and there can be more than 1 'Documents' table in a database.
can someone show me the script to do it?
Thanks.
 
 

View 6 Replies View Related

Transact SQL :: Renaming Pivot Table Column Names Dynamically

Oct 30, 2015

I got a table which gets populated by stor proc where we pivot the Sum(Balance of mortgage) by YYYYMM for the whole duration of the loan term.

I have a requirement to rename the column header where the previous month end balance period be renamed to P0.

if we run the report today, then the balance as at 31/09 should show under column P0 which now shows under 201509 and then P0 keeps shifting with each month run.

How do I dynamically rename the column headers.

View 7 Replies View Related

Store Procedure To Load Data From Flat File To Staging Table Dynamically - Column Metadata

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

ALTER TABLE DROP COLUMN LastUpdated Failed Because One Or More Objects Access This Column.

Mar 7, 2008

Hi I’m trying to alter a table and delete a column I get the following error. The object 'DF__Morningst__LastU__19EB91BA' is dependent on column 'LastUpdated'.
ALTER TABLE DROP COLUMN LastUpdated failed because one or more objects access this column. I tried deleting the concerned constraint. But the next time I get the same error with a different constraint name. I want to find out if I can dynamically check the constraint name and delete it and then drop the column. Can anyone help.IF EXISTS(SELECT 1FROM sysobjects,syscolumnsWHERE sysobjects.id = syscolumns.idAND sysobjects.name = TablenameAND syscolumns.name = column name)BEGIN EXECUTE ('ALTER TABLE tablename DROP CONSTRAINT DF__SecurityM__DsegL__08C105B8')EXECUTE ('ALTER TABLE tablenameDrop column columnname)ENDGO
 

View 1 Replies View Related

Reporting Services :: Change Column Size Dynamically Depends On Content Of The Column?

Jun 4, 2015

How to change column size dynamically depends on content of the column.

View 2 Replies View Related

Data Access :: How To Find Column Names In A Table

Sep 11, 2015

how to find the columns names in a table in sql 2008r2.

as i need to compare the midsing fields in the table from two database.

View 3 Replies View Related

DTS Table From Access To SQL, Identity Column Error. Should Be Easy, But I Can't Figure It Out.

Oct 4, 2007



I am trying to move data from Access to SQL Server 2000 using DTS.

I have an Access Source and SQL Server Desitination, My destination table has a field called tableID that is not in the source. TableID is a Primary Key and an Identity column.

I have Enable Identity Insert checked in the options of the Transform Data Task.

When I execute ythe task, I get the error

"Cannot insert the value NULL into column 'TableID'. Does not allow nulls. Insert Fails.

Does anyone know why this simple task would fail?

Mike


View 6 Replies View Related

Dynamically Exporting Data To Access File

Jun 19, 2007

I am looking a way to export SQL Server 2005 DB tables to Access file dynamically. Like if i have added or removed any tables from SQL DB then when i run SSIS package it should export that table with data to Access file. is there any easy way to do this. if it is not them please someone please tell me which controls should i look at and which technique i should use to do this.

View 4 Replies View Related

Data Access :: Column Name Or Number Of Supplied Values Does Not Match Table Definition

Jun 22, 2015

I'm executing a stored procedure but got error :

Msg 213, Level 16, State 1, Procedure ExtSales, Line 182
Column name or number of supplied values does not match table definition.

View 5 Replies View Related

How To Set Column Name Dynamically?

Oct 18, 2006

HI chaps

my scenario is that, i have a table in which i have column such as col01,col02,col03....col31

i want to retrieve the records related to that column by specifying the name dynamically (by using loop) as fist three character are same ('col??') and i have to do integer increment in last two character (???01...???31). Is it possible that I can use variable for column name?, if yes how? or is there any other way to achieve this task ?

waiting for your reply

regards

View 7 Replies View Related

Choose A Column Dynamically

Mar 3, 2008

I want to choose a column dynamically depending on a session variable.
In other words, each customer has a different price level. so I need to choose the column that corresponds to thier price level in thier customer record
Any help is appreciated.
below is my futile attempt
 
SelectCommand="SELECT cove.CATALOG.ITEM_NO,cove.catalog."& <%#= session("pl") %> & ", cove.CATALOG.DESCRIPTION, cove.CATALOG.DESCRIPTION2, cove.CATALOG.DESCRIPTION3, cove.PRODLINE.DESCRIPTION AS Expr1, cove.CATALOG.GRP, cove.COMPANY.PRL, cove.COMPANY.COMPANY FROM cove.CATALOG INNER JOIN cove.COMPANY ON cove.CATALOG.WEB_STATUS <>'[I]' cove.COMPANY.I LEFT OUTER JOIN cove.PRODLINE ON cove.CATALOG.PRODLINE = cove.PRODLINE.CODE WHERE (cove.COMPANY.COMPANY = @company) AND (cove.CATALOG.GRP <> '[ACC]')">
<SelectParameters>

View 3 Replies View Related

Dynamically Select Column

Sep 29, 2004

Hey all. I'm trying to create a stored proc that will update a variable column, depending on the parameter I pass it. Here's the stored proc:


CREATE PROCEDURE VoteStoredProc
(
@PlayerID int,
@VoteID int,
@BootNumber nvarchar(50)
)
AS

DECLARE @SQLStatement varchar(255)
SET @SQLStatement = 'UPDATE myTable SET '+ @BootNumber+'='+ @VoteID + ' WHERE (PlayerID = '+ @PlayerID +')'

EXEC(@SQLStatement)

GO


I get the following error:

Syntax error converting the nvarchar value 'UPDATE myTable SET Boot3=' to a column of data type int


The update statement is good, because if I use the stored proc below (hard-coded the column), it works fine.

CREATE PROCEDURE VoteStoredProc
(
@PlayerID int,
@VoteID int,
@BootNumber nvarchar(50)
)
AS

UPDATE
myTable
SET
Boot3 = @VoteID
WHERE
PlayerID = @PlayerID
GO


Is there a way to dynamically choose a column/field to select from? Or is my syntax incorrect..?
Thanks!

View 2 Replies View Related

How To Seelct Column Name Dynamically

Jan 14, 2008

am passing column name as parameter, so i wanted to select column name dynamically.

eg: select columname1,columname2 where @param = columnname1,columnname2.
when @param =columnname1,columnname2. select should be of respective column. if @param = columname2,columnname8, then select columname2,columnname8 from table1 where coulmnname2='1' and columnname8='2'.

love all

View 5 Replies View Related

Change Column Name Dynamically

Nov 30, 2007



Hi All,
I have a series of tables need to import to server. When creating the target tables, I want to change the columns name as well, for example:
Source table column Target table column


Name FN_Name
Age FN_Age

The problem is I suppose I don't know the columns name in source table, I want to the tasks scan the source table and make the change programmlly.

Which tasks or approaches can be used to implement this?

Thanks
Micror

View 6 Replies View Related

Set Inputcollection Column Value Dynamically

Mar 21, 2007

I'm looping through Me.ComponentMetaData.InputCollection(0).InputColumnCollection... and get the column name of the inputcollection in a script component. Now, what i want to do is set a value to all of the input columns using a loop. If the type is an int, set it to 1, if string then set it to "1". Anyway to approach this problem?



Thanks!

View 1 Replies View Related

Writting Column Names Dynamically

Feb 28, 2008

Can someone please help I'm writting the following query.
SELECT
(SELECT c.column_name FROM information_schema.tables T
JOIN information_schema.columns C
ON t.table_name = c.table_name
WHERE t.table_type = 'base table' and t.table_name like 'L_%' )
INTO #TempTable FROM TableA A LEFT JOIN [Server-Name].DB_Name.dbo.TableB B ON A.ID = B.ID

I'm trying to put commas between column names. How do I go about doing that?

View 16 Replies View Related

Adding Identity Column Dynamically

Nov 23, 2005

Hi,In my stored procedure I'm doing a SELECT onINFORMATION_SCHEMA.TABLE_CONSTRAINTS. However there is no unique id onthis table, so I was wondering if it was possible to add it dynamicallyin my SELECT, so that I would assign a unique id to each recordreturned by my SELECT?Thanks for your support.

View 3 Replies View Related

Dynamically Changing Column Headings

Feb 5, 2008

We have a query in which we have data in fields called TS1Min, TS1Max, TS1Avg, TS2Min, TS2Max, TS2Avg etc.

We have a different table in which we define that vale of TS1, TS2, as an example TS1 might equal RED, TS2 might equal BLUE.

We have written a query that puts TS1Min, TS1Max, TS1Avg, TS2Min, TS2Max, TS2Avg in a temp table #TEMPA

and we also put the values of RED and BLUE in another temp table #TEMPB

now we want to select * from #TEMPA but rename the headings TS1Min to display RED-TS1Min, TS1Max as RED-TS1Max, TS1Avg as RED-TS1Avg etc...

any ideas on how to do this

View 4 Replies View Related

Create Target Table Dynamically Based On Source Table Schema?

Sep 13, 2005

I’ve got a situation where the columns in a table we’re grabbing from a source database keep changing as we need more information from that database. As new columns are added to the source table, I would like to dynamically look for those new columns and add them to our local database’s schema if new ones exist. We’re dropping and creating our target db table each time right now based on a pre-defined known schema, but what we really want is to drop and recreate it based on a dynamic schema, and then import all of the records from the source table to ours.It looks like a starting point might be EXEC sp_columns_rowset 'tablename' and then creating some kind of dynamic SQL statement based on that. However, I'm hoping someone might have a resource that already handles this that they might be able to steer me towards.Sincerely, 
Bryan Ax

View 9 Replies View Related

Transact SQL :: Dynamically Alter Schema Of Stage Table When Source Table Structure Changed?

Oct 25, 2015

we have a table in our ERP database and we copy data from this table into another "stage" table on a nightly basis. is there a way to dynamically alter the schema of the stage table when the source table's structure is changed? in other words, if a new column is added to the source table, i would like to add the column to the stage table during the nightly refresh.

View 4 Replies View Related

SQL Server 2012 :: Return A Table Of Table-names Dynamically?

Sep 14, 2015

I have a function that returns a table from a comma-delimited string.

I want to take this a step further and create a function that will return a set of tablenames in a table based on a 'group' parameter which is a simple integer...1->9, etc.Obviously, what I am doing is not working out.

CREATE FUNCTION dbo.fnReturnTablesForGroup
(
@whichgroup int
)
RETURNS @RETTAB TABLE (
TABLENAME VARCHAR(50)

[code]....

View 9 Replies View Related

How To Change Column Names Dynamically In UNPIVOT TASK

Apr 10, 2008

Dear All,

We are using UnPivot task to convert the columns into rows using the Excel File as source. But the Excel file column names are changing frequenly sometimes its having only 4 columns sometimes its 10 columns.

Everytime we are checking and unchecking the column list in Unpivot Task.

can anybody help us to solve this issue that Unpivot task should take the column name dynamically.

Thanks,
Syed

View 1 Replies View Related

How Do I Call A Sql Column Dynamically With A Checkbox And Search Term In Textbox

Jan 25, 2008

 hi, I have a question regarding calling sql table columns dynamically? workflow would go as:1. user enters search term into a textbox2. user checks a checkbox to search by column in sqldb (eg.. firstname or surname) pseudo sql would go like......SELECT +%column1(checkbox1.value)%+ OR +%column2(checkbox2.value)%+ OR +%column3(checkbox3.value)%+WHERE  column1 = +%TextBox.Text%+ OR column2 = +%TextBox.Text%+ 3. display results in gridview my sql needs to improve greatly so any code insight(good book or link) would be terrific . thanks  

View 10 Replies View Related

T-SQL (SS2K8) :: Dynamically Delete Data Based On Date Column

May 19, 2015

DELETE FROM Report_temp2
WHERE MSSalesID in
( Select Report_temp.MSSalesID FROM Report_temp)

DELETE FROM Report_temp
WHEREMSDate < '2015-07-01'

Actually the year stating form july.

Q1 is july,aug,sep.
Q2 is oct nov,dec.
Q3 is jan,feb,mar.
Q4 is april, may,june.

So what I need is dynamically I want to delete the data every year prior to current year.

View 4 Replies View Related

Change Chart Type Dynamically From Column To Line Graph??

May 1, 2006

I am developing several charts with column type and sub type as stacked. There is a requirement from the users that they want an option to choose the type of chart.

Is it possible to change chart type dynamically from say Column type to Line type based on user option in front-end?

Any help will be appreciated.

Thanks in advance !!

View 5 Replies View Related

Reporting Services :: How To Generate Column Name Dynamically In SSRS Report

Oct 5, 2015

I have to display three months name as column name in ssrs reports. These month column will be dynamically. So i have to display the column dynamically.

View 3 Replies View Related

Integration Services :: Create Excel With Sheet-name And Column Name Dynamically?

Jun 27, 2015

how to create excel with sheetname and column name dynamically

View 4 Replies View Related

Creating Table Fields Dynamically From Another Table Row

Aug 31, 2006

Hello all:

Is it possible to creates fields of the table dynamically?. I have this situation in my project. This is just a small sample. I have row of length 140. I don't wan't to declare all this fields manually using the create table command.

The description of table is as, in this table all the field are of type varchar only, there are like 140 columns.

create dummy emp (
field1 VARCHAR(100), field2 varchar(200), field3 VARCHAR(100).... )

Table: Dummy
================================================== ==
field1 field2 field3..........
Empid Empname empaage1 sam 23...........
2 rai 22............
.
.
.
n raj 45.............
================================================== ==
Now I want to create another table as "EMP" , with proper data type
fields too..

create table emp (
empid int, empname varchar(100), empage int....)

The table should look like as:

Table: EMP
================================================== ==
Empid Empname empaage............
1 sam 23...............
2 rai 22................
.
.
.
n raj 45.................
================================================== ==

I want to do this dynamically.....
Some how I need to extract those field from table[dummy]; the first row acts as a column header for the table[Emp] and the subsequent row acts as a record for the table[Emp]

A small rough snippet of the code will be appreciated....

Waiting for replies........
saby

View 1 Replies View Related

Reporting Services :: How To Adjust Column Length Dynamically In SSRS Report

Nov 11, 2015

I developed a SSRS report, the problem is i dont have data in DEV server. So i dont know how to adjust the column lengths in ssrs report. is there any property so that the column length can be adjusted dynamically based on the data length whenever data is available in production.

View 3 Replies View Related

Splitting SQL Server Date/Time Column Into Access Date Column And Access Time Column

Jan 24, 2008

I have an SSIS package that moves data from SQL Server to an legacy Access database. In SQL Server, there is a date/time column that I need to split into a separate date column and time column in the access database. Initially I just created a derrived column for the time and set the expression equal to the source date/time column from SQL Server. Unfortunately, that just makes the date column and time column the same having the full date/time.

What expression can I use during a derrived column transformation to assign just the date to a derrived column and just the time to another derrived column?

Thanks,

Steve

View 3 Replies View Related

Pivot That Increases Columns Dynamically With Column Header As Boundary Date For Each Week

Dec 5, 2007

Hi All,

The current/ Base table would be like below,





Products

level

Date


N1

b

11/5/2007


N2

p

11/6/2007


N3

p

11/7/2007


N4

p

11/14/2007


N5

b

11/15/2007


N6

p

11/23/2007




Expected Result.







<=11/7/2007

<= 11/14/2007

<=11/21/2007


b

1

1

2


p

2

3

4


Total

3

4

6




As you can see, the above table has cumulative data.
1. It calculates the number of Products submitted till a particular date- weekly
2. The date columns should increase dynamically(if the dates in base table increases) each time the query is executed
For ex: the next date would be 11/28/2007
I tried something like, it gives me count of €˜b€™ level and €˜p€™ level products by week
declare @date1 as datetime
select @date1 = '6/30/2007'
while (@date1 != (select max(SDate) from dbo.TrendTable))
begin
set @date1 = @date1 + 7
select Level, count(Products)
from
dbo.TrendTable
where SDate < @date1
group by Level
end
what I think is required is a pivot that dynamically adds the columns for increase in date range.
/Pls suggest if any other way of achieving it.
Pls help!!!

Thanks & Regards

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved