Transact SQL :: Select Column By Ordinal Position

Apr 16, 2012

Is there any way to select columns by ordinal position rather than by name?

Something like
Select t.[1] as col1, t.[2] as col2
FROM table t

The question comes because of a very specific situation where I've got 2 databases that have exactly the same schema at a column/datatype level but the column names are different.   There are a few other ways to skin the cat but I'm interested if it can be done this way - without a join to syscolumns.

View 12 Replies


ADVERTISEMENT

Change Ordinal Position Of The Column

Jun 18, 2008

1 have a table with 74 colun.But due to some deletion i have the ordinal postions as
1
2
3
.
.
69
70
72
73
74
76

what i wants is to change the ordinal from 72 to 71,73 to 72,74 to 73,76 to 74

SELECT @field = 0, @maxfield = max(ORDINAL_POSITION) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName
-- handle insert case here
SELECT @field = min(ORDINAL_POSITION) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName and ORDINAL_POSITION > @field
SELECT @bit = (@field - 1 )% 8 + 1
SELECT @bit = power(2,@bit - 1)
SELECT @char = ((@field - 1) / 8) + 1
--IF substring(COLUMNS_UPDATED(),@char, 1) & @bit > 0 or @Type in ('I','D')
IF substring(COLUMNS_UPDATED(),@char, 1) & @bit > 0 or @Type in ('D') -- For the insertion case don't save the iserted data.


I needed it as i have a trigger whihc is adding value in a log table on update but due to this problem it fails for certain column

Trgger is solme thing like

WHILE @field < @maxfield
BEGIN
SELECT @field = min(ORDINAL_POSITION) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName and ORDINAL_POSITION > @field
SELECT @bit = (@field - 1 )% 8 + 1
SELECT @bit = power(2,@bit - 1)
SELECT @char = ((@field - 1) / 8) + 1
--IF substring(COLUMNS_UPDATED(),@char, 1) & @bit > 0 or @Type in ('I','D')
IF substring(COLUMNS_UPDATED(),@char, 1) & @bit > 0 or @Type in ('D') -- For the insertion case don't save the iserted data.
BEGIN
IF @Type not in ('I')
BEGIN
SELECT @fieldname = COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName and ORDINAL_POSITION = @field -1
--print('fieldname = '+@fieldname)
SELECT @sql = 'insert Audit (ActionTypeID, RowID, TableName, PK, FieldName, OldValue, NewValue, UpdateDate,UserID, UserName, UserType)'
SELECT @sql = @sql + ' select convert(bigint,' + @ActionTypeID + ')'
SELECT @sql = @sql + ',' + @RowID
SELECT @sql = @sql + ',''' + @TableName + ''''
SELECT @sql = @sql + ',' + @PKSelect
SELECT @sql = @sql + ',''' + @fieldname + ''''
SELECT @sql = @sql + ',convert(varchar(1000),d.' + @fieldname + ')'
SELECT @sql = @sql + ',convert(varchar(1000),i.' + @fieldname + ')'
SELECT @sql = @sql + ',''' + @UpdateDate + ''''
SELECT @sql = @sql + ',' + @UserID
SELECT @sql = @sql + ',''' + @UserName + ''''
SELECT @sql = @sql + ',''' + @UserType + ''''
SELECT @sql = @sql + ' from #ins i full outer join #del d'
SELECT @sql = @sql + @PKCols
SELECT @sql = @sql + ' where i.' + @fieldname + ' <> d.' + @fieldname
SELECT @sql = @sql + ' or (i.' + @fieldname + ' is null and d.' + @fieldname + ' is not null)'
SELECT @sql = @sql + ' or (i.' + @fieldname + ' is not null and d.' + @fieldname + ' is null)'
--print('@sq=====sdfdfsfsdf')--sha
--print(@sql)--sha
EXEC (@sql)
END
END
END

Kamran Shahid
Sr. Software Engineer(MCSD.Net)
www.netprosys.com

View 9 Replies View Related

Getting Data Based On Ordinal Position Of The Column In The Table

Aug 30, 2007

Hi
I am having a problem in auditing the column data in tables.My requirement is i have write a trigger which is capable of auditing the columns which are going to be added in the future also with out using dynamic SQL.is there any way to do so.
I feel if i can get the column data based on ordinal position then it is possible.
Can any body suggest.
My set Up is like this
I have a base_table to be audited.
I have a Audit_spec table which contains name of the table and columns to be audited.
And Audit table which actually captures the table name,column name ,old value and new value.
I have to audit only those columns in the Audit_spec spec.
If schema changes(Like new column added) happens to base_table and I want that column to be audited.with out any changes to my trigger code i should handle the newly added column ..





View 6 Replies View Related

Ordinal Position

Jul 20, 2005

Is there a neat way to find an ordinal value from a table,for example the median or 95th percentile value in a column,without walking through the table in ascending or descendingorder?Thanks,Jim GeissmanCountrywide Home Loans

View 1 Replies View Related

Transact SQL :: Item Cannot Be Found In Collection To Requested Name Or Ordinal

Sep 1, 2015

I have a storeprocedure( sp_nthWorkingday)  which return a calender date.
eg :
calendardate
9/9/2015

I wrote a dts script for displaying this date.Below is the code.

Function Main()
dim myConn
dim myRecordset
dim iRowCount

[code]....

But I am getting an error on execution.Error : item cannot be found in the collection to the requested name or ordinal  

View 2 Replies View Related

Microsoft.SqlServer.Dts.Pipeline.PipelineBuffer Column Ordinal From Name?

Oct 27, 2006

Hi,

I need to access columns from a data flow by ordinal position in a script transformation (I'm parsing an excel file which has several rowsets across the page). The first problem I encountered is the generated BufferWrapper does not expose the columns collection (i.e. Input0Buffer(0) does not work) but I got around that by implementing my own ProcessInputs(InputId, Buffer) method instead of using the wrapper.

My problem now is that the column ordinals are in some random order (i.e. Column "F1" is ordinal 1 but Column "F2" is 243). Where in the object model can I map between the name and the ordinal - it's not jumping out at me?

Dave



PS Why is the script editor modal, it's frustrating having to switch between the Visual Studio environment and the VSA one.

View 3 Replies View Related

Transact SQL :: Calculate Data Based On Position

Jun 4, 2015

I have a table "PrintArea" with below table structure.

The Details column have " " separated data.

CREATE TABLE [dbo].[PrintArea](
[ID] [int] IDENTITY(1,1) NOT NULL,
[AccessDate] [datetime] NULL,
[IPAddress] [varchar](16) NULL,
[SerialNum] [varchar](256) NULL,
[Description] [varchar](256) NULL,
[Details] [varchar](2048) NULL,
)

This is how the data lookis like.

INSERT [dbo].[PrintArea] ([ID], [AccessDate], [IPAddress], [SerialNum], [Description], [Details]) VALUES (104280, CAST(0x0000A28A00A88310 AS DateTime), N'70.89.39.161', N'InSign-f529c824-85a6-4a64-8c59-e9f786d718f3-YM2AS31367,BFEBFBFF000306A9', N'Printing', N'Headboard_Insert_4
1
1
7938
5579

[Code] ...

I want to calculate totalAreaPrinted based on below formula from Details column.

View 2 Replies View Related

Transact SQL :: Select Row With Max (column Value) Group By Another Column

May 19, 2015

i dont't know how to select row with max column value group by another column. I have T-SQL

CREATE PROC GET_USER AS
BEGIN
SELECT T.USER_ID ,MAX(T.START_DATE) AS [Max First Start Date] ,
MAX(T.[Second Start Date]) AS [Max Second Start Date],
T.PC_GRADE,T.FULL_NAME,T.COST_CENTER,T.TYPE_PERSON_NAME,T.TRANSACTION_NAME,T.DEPARTMENT_NAME ,T.BU_NAME,T.BRANCH_NAME,T.POSITION_NAME
FROM (

[code]....

View 3 Replies View Related

Transact SQL :: Add Position Of Record Based On Certain Date Of Transaction

Aug 4, 2015

I built the following query to add the position of a record based on a certain date of the transaction of a customer:

select
CustomerID
, Product
, purchasedate

[code]....

View 6 Replies View Related

DTS Select Using Record Position

Jul 20, 2005

Hi there, it has been a while since i have posted. I am in asituation where I am stumped. I am learning to build a dts packagewhere I am connecting to a table in an AS400. This database is beingmaintained by an outsourced company and therefore I can't change thetable structure or even ask them to. Anyway, this table currently hasabout 104,000 records. I am building a package to check it and pullout the most recent records and put them where they go in my SQLServer 2000 tables. The only way I can think of to get the mostrecent records is to use a global variable in the package to rememberthe record count and then get those records from that record positionon. Problem is, I have no idea how I would go about selecting recordsfrom a record position. Does anybody have any ideas or should I beusing a different approach? There are no time stamps to work from. Iwas told that the AS400 records, including updates, are appended tothe table, which is why I thought this approach made sense. I wouldtruly appreciate any help.

View 1 Replies View Related

Transact SQL :: Select Column On Condition

Jul 4, 2015

I have a table called names  (firstname, lastname, number) then i have a DECLARED variable called  @displaynum...If @displaynum id true   my select query should select the number column.  if the variable is false , only the first two columns are selected.

e.g   @displaynum = true                                          
@displaynum = false
Firstname  | Lastname | number                               Firstname  | Lastnam

blah           |   blah        |   12345                             
blah           |  blah

i am not sure if this is possible as a case still selects the column but just changes the values.

View 12 Replies View Related

Transact SQL :: Custom Column In Select Statement

Aug 12, 2015

I want to add a custom column in a select statement that has a value to true or false based on other criteria.

SELECT [ID], [Name], [Description], [EmpID], [Employed] FROM [Employees]

Now, in the above example there is no [Employed] Column in my table but I want it to show true or false based on whether or not [EmpID] equals a certain value.

View 6 Replies View Related

Transact SQL :: How To Select Number For Varchar Column

Sep 15, 2015

I have a table with number and varchar columns. The last insert statement has 1 inserted.

The  select statement should retrieve    

a          b                                                          
1         1

CREATE TABLE [dbo].[test1](
 [a] [int] NULL,
 [b] [varchar](10) NULL
) ON [PRIMARY]
  insert into test1 values (1,'a')
  insert into test1 values (2,'b')
  insert into test1 values (4,'d')
  insert into test1 values (12,'x')
  insert into test1 values (15,NULL)
  insert into test1 values (1,1)

View 5 Replies View Related

Column Position Sql Table

Jul 26, 2007

 There are about 500 tables in one particular datbase. There are
foreign keys set on most of the tables. I want to change the position
of the primary key column in all those tables. How can I do that
programatically?

View 6 Replies View Related

Can We Interchange The Column Position In Sql

May 26, 2008

HI All,
can we interchange the column position in sql.

View 4 Replies View Related

Swap Column Position

Jul 20, 2005

What is a good method/mechanism to swap the position of multiplecolumns?For instance, tblXZY has the followings columns and respectivepositions:tblXZY======xyzUUID 1fn 2ln 3phone 4email 5city 6state 7....Now, I need to make city as 2 and state as 3. BTW, the tblXYZ tablehas data there. Copy/select all the data into a new table withdesired column position would require constraints re-mapping etc.,which seems quite a bit hassle.Thanks.

View 6 Replies View Related

Add Column In Specific Position

Dec 12, 2007

What is the SQL for adding a column at specific location?

eg
TableA
colA
colB

I want to add colC after colA.


Thanks,
Max

View 1 Replies View Related

Transact SQL :: SELECT Unique Values In Single Column?

Jun 8, 2015

I have the following two tables...

tblServer
-serverID
-serverName
-serverLocation
tblSite
-siteID
-serverID
-siteName
-siteIpAddress

I need to write a select query that gets the values of all columns but only returns unique sites because some sites are load balanced across several servers and where this is the case I don't want the site to appear multiple times in the list.

View 4 Replies View Related

Transact SQL :: How To Select Data With Specific Priority Of A Column

Aug 1, 2015

i have table that has rows as below

DECLARE @Table TABLE
(minv_code INT,
alert_msg varchar(10),
alert_time Datetime)

[code]...

i want to select the data priority wise. the o/p should look like 

e.g first row - 873939, 'Meter', '7/24/2015 3:31:22'
second row - 873939, 'Tamper', '7/24/2015 3:30:00'
third row - 873939, 'Reverse', '7/24/2015 3:31:18'
fourth row -873940, 'Tamper', '7/24/2015 3:31:22' 
fifth row - 873940, 'Reverse', '7/24/2015 3:30:00'

View 6 Replies View Related

Can I Move Some Column Position By Using SQL Command ?

Jun 1, 2007

I created SQL table follow by XSD fileAnd when any users added new column to XSD in ordinal position = 3 But after my program successfully created new column, its position is the last position  What can I do ???? I suspect  why I can't set it (I've looked for solution on MSDN already)even though We can see ordinal position bythis query  SELECT *FROM INFORMATION_SCHEMA.Columns   What can I do for solving ???? Help me please 

View 1 Replies View Related

TSQL Change The Position Of A Column?

Dec 16, 2004

We have a little app to help us move applications from developent --> stage --> production. It uploads the files, runs the new stored procedures etc.

One of the things it does is create new columns in existing tables. In EM you can create a new column in any position, but ALTER TABLE seems to only add columns to the end of the table. Is there a way in TSQL to create columns in arbitrary positions in the table? Or do I have to recreate the whole table?

View 2 Replies View Related

Transact SQL :: Select Multiple Columns From Table But Group By One Column

Jun 17, 2015

I have a SQL query like this

select CurrencyCode,TransactionCode,TransactionAmount,COUNT(TransactionCode) as [No. Of Trans] from TransactionDetails where CAST(CurrentTime as date)=CAST(GETDATE()as date) group by TransactionCode, CurrencyCode,TransactionAmount order by CurrencyCode

As per this query I got the result like this

CurrencyCode TransactionCode TransactionAmount No.OfTrans
AED     BNT    1     1
AED     BNT     12     1
AED     SCN     1     1
AED     SNT     1     3

[Code] ....

But I wish to grt result as

CurrencyCode TransactionCode TransactionAmount No.OfTrans
AED     BNT   13     2
AED     SCN     1     1
AED     SNT     11     7
AFN     BPC    8     6

[Code] ....

I also tried this

select CurrencyCode,TransactionCode,TransactionAmount,COUNT(TransactionCode) as [No. Of Trans]
from TransactionDetails where CAST(CurrentTime as date)=CAST(GETDATE()as date)
group by TransactionCode order by CurrencyCode

But of course this codes gives an error, but how can I get my desired result??

View 5 Replies View Related

Transact SQL :: Returning Multiple Values From Column In Select Statement?

Nov 26, 2015

I am writing a query and have the bulk of it already written. 

I am looking at a table that contains customer orders. There is a column named Customer_Order.Status Available values for this column is R, F, H, and C.

I'd like for my query to return all lines that have the value R, F, H.

My where clause is written like this 

WHERE CUSTOMER_ORDER.SITE_ID = 'XXX' AND CUSTOMER_ORDER.STATUS = ('R','H','F')

I know I'm missing something....

View 3 Replies View Related

Any Function That Returns The Position Of A String In A Column?

Dec 12, 2007

Hello!
Is there a function that gets the name of a column and a string as arguments and returns the position of this string in the column given?

Thank you in advance.

View 1 Replies View Related

Transact SQL :: Generate Insert With Column List And Select With Columnlist Statements

Oct 22, 2015

I had to enable identity_insert on a bunch of tables and I have already done that. Now I need to modify my insert into select * from statements to include column list names along with identity columns for select as well as insert statements. The DDL is same but they are both different databases.There are almost 100 tables that it needs to be modified. Is there a way we can generate scripts for insert and select for each individual table along with their column lists including the identity column?

View 7 Replies View Related

Stacked Column Chart Label Position Problem

Feb 26, 2008

I have a Stacked Column graph and when we set the Position of the Point Label to be "Top Center", the Point Label always stays in the center of that particular Bar.

On a easier, basic Bar chart, the Point Label setting works correctly.

Has anyone else had a similar issue or know if this is a known issue ?

View 2 Replies View Related

Transact SQL :: Select Specific Values From All Rows Where Value Of A Specific Column Is (Active)

May 23, 2015

I need to select specific values from all rows where the value of a specific column is "Active"

This part works: SELECT LastName, FirstName, MiddleInit, ClientId FROM dbo.Client

But I want to add: WHERE StatusType = (Active) and how to do this.

View 4 Replies View Related

Transact SQL :: How To Select Rows From Table Where DATE Column Is Today's Date

Aug 31, 2015

So my data column [EODPosting].[MatchDate] is defined as a DATE column. I am trying to SELECT from my table where [EODPosting].[MatchDate] is today's date.

SELECT*
FROM[dbo].[EODPosting]
WHERE[EODPosting].[MatchDate]=GETDATE()

Is this not working because GETDATE() is like a timestamp format? How can I get this to work to return those rows where [EODPosting].[MatchDate] is equal to today's date?

View 2 Replies View Related

Transact SQL :: SELECT On Column Name From Query Result Set In Same Query?

May 9, 2015

I have a column colC in a table myTable that has a value (e.g. '0X'). The position of a non-zero character in column colC refers to the ordinal position of another column in the table myTable (in the aforementioned example, colB).

To get a column name (i.e., colA or colB) from table myTable, I can join ("ON cte.pos = cn.ORDINAL_POSITION") to INFORMATION_SCHEMA.COLUMNS for that table catalog, schema and name. But I want to show the value of what is in that column (e.g., 'ABC'), not just the name. Hoping for:

COLUMN_NAME Value
----------- -----
colB        123
colA        XYZ

I've tried dynamic SQL to no success, probably not executing the concept correctly...

Below is what I have:

CREATE TABLE myTable (colA VARCHAR(3), colB VARCHAR(3), colC VARCHAR(3))
INSERT INTO myTable (colA, colB, colC) VALUES ('ABC', '123', '0X')
INSERT INTO myTable (colA, colB, colC) VALUES ('XYZ', '789', 'X0')
;WITH cte AS
(
SELECT CAST(PATINDEX('%[^0]%', colC) AS SMALLINT) pos, STUFF(colC, 1, PATINDEX('%[^0]%', colC), '') colC

[Code] ....

View 4 Replies View Related

Ordinal Question

Aug 29, 2006

Hi guys,

How to produce ordinal numbers in sql query?

Say I have a table for a Building. My floor numbers are intergers, 1,2,3,4 and so on. When I run the query, the result I need is like this:

1st
2nd
3rd
4th
5th
...
23rd
....

How will I do this?

Thank you.

View 17 Replies View Related

Ordinal Number In Results

Jan 13, 2006

I would like to add a field to a query that returns an ordinal number indicating which row of the results it is. Anybuddy know how?
eg. 1,2,3,4,5,6,7....

Thanks,
Carl

View 2 Replies View Related

Sqlmangr.: The Ordinal 29 Could Not Be Located In

Apr 24, 2006

Dear all

I've received the following error on the startup of SQL SERVER. Repeating the error when trying to start Service Manager.

sqlmangr.exe : The ordinal 29 could not be located in the dynamic link library odbcbcp.dll

Can someone help me to solve it

View 1 Replies View Related

Transact SQL :: Calculate DateTime Column By Merging Values From Date Column And Only Time Part Of DateTime Column?

Aug 3, 2015

How can I calculate a DateTime column by merging values from a Date column and only the time part of a DateTime column?

View 5 Replies View Related







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