How to looping through table and concatenate in t-sql or sql server?

Posted on 2014-09-15
Medium Priority
Last Modified: 2015-02-11

I need to loop through a table (Table1) and as it goes through each single record to concatenate 3 columns (date, time and code) it has to  create a unique column(Primary Key) .

Two questions:

1) Is this a proper of looping on row of a table?
2) why am I getting error as following?

Msg 4104, Level 16, State 1, Line 11
The multi-part identifier "Table1.Date" could not be bound.
Msg 4104, Level 16, State 1, Line 12
The multi-part identifier "Table1.Time" could not be bound.
Msg 4104, Level 16, State 1, Line 13
The multi-part identifier "Table1.code" could not be bound.


while (select count(*) from Table1) > 0

	declare @dt as varchar(10)
	declare @ti as varchar(11)
        declare @code as varchar(11)

	set @dt = Table1.Date
	set @ti = Table1.Time
	set @code = Table.code
	set @dt = REPLACE(@ti, '/','')
	set @ti = REPLACE(@ti, ':','')
	set @code = REPLACE(code, '.','')

   select comb = @code + @dt + @dt

Open in new window

Question by:akohan
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

Expert Comment

ID: 40324367
Not sure exactly but...a CTE would run a lot faster.

Anyway here is a looping example.

      RowID bigint identity (1,1)
      , TheDate datetime
      , TheCode varchar(50)

DECLARE @x bigint

INSERT INTO @t      


            CONVERT(varchar(50), TheDate, 110) + '_' + TheCode
      FROM @t
      WHERE RowID = @x

      SET @x = (SELECT MIN(RowID) FROM @t WHERE RowID > @x)
LVL 13

Accepted Solution

Russell Fox earned 1600 total points
ID: 40324375
There's no need to do a loop for this, it will only slow you down. Run this to see if it gives you what you need. Note that you can also just add a new IDENTITY or UNIQUEIDENTIFIER column if you just need uniqueness. Your method DOES NOT guarantee uniqueness:
	[ID] VARCHAR(50), 
	[Date] VARCHAR(10), 
	[Time] VARCHAR(11), 
	[Code] VARCHAR(11)

INSERT INTO @Table1 (Date, Time, Code)
	VALUES ('6/1/2014', '16:43:04.79', 'some1.thing'),
		('6/2/2014', '16:44:04.80', 'some2.thing'),
		('6/3/2014', '16:45:04.81', 'some3.thing'),
		('6/4/2014', '16:46:04.82', 'some4.thing'),
		('6/5/2014', '16:47:04.83', 'some5.thing')
UPDATE @Table1
	SET ID = REPLACE(REPLACE(REPLACE(Code + [Date] + [Time], ':', ''), '.', ''), '/', '')

FROM @Table1

Open in new window


Author Comment

ID: 40324385
Hi skillilea,

What is CTE?
Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.


Author Comment

ID: 40324386
Hi Russel,

Yes, I need uniqueness so should I change the column type to IDENTITY? then run your example?

Assisted Solution

skillilea earned 400 total points
ID: 40324389
If you are looking for a unique column set the column to a UNIQUEIDENTIFIER.  Or increment a BIGINT and make it an identity.

SQL does this for you so you don't need to jump through the hoops you are trying to create.

CTE = Common Table Expression.   Can use this technique to replace most loops.

Russel did it best above it you really need to add a field to your table.


Author Comment

ID: 40324394
Ok, I understand what you are saying now but let me explain my situation.


I'm getting a a huge list from IIS log file which has thousands of rows on daily basis.  I'm reading the IIS log file and then import them in a table (temporary) which you see here. Now, from here I need to break the information in several tables. One of them is Visitors table. Each visitor is recognized by unique id which I thought ip+date+time would be fine.

Now, are you saying instead of creating combination of date, time, ip i create a unique column in Visitor table? if make sense but can I keep this key in other tables as foreign key?
if so, how can I keep this id to create a relational case between this table (visitor) and table (UrlVisited) table?

LVL 49

Expert Comment

ID: 40324482
Well, you still want to avoid deliberate looping through code of your own - if you can - and you can here.

Let the product do the looping for you (think of a sql command as looping row by row automatically)

e.g. this would update those 3 fields in table1

UPDATE Table1 /* "loop" through this table, updating each row */
     Table1.Date = REPLACE(Table1.Date, '/','')
   , Table1.Time = REPLACE(Table1.Time, ':','')
   , Table1.code = REPLACE(Table1.code, '.','')

On the broader question of design I don't think I have enough understanding to offer a definite opinion. If your current design of ip+date+time does provide uniqueness then you may not want to change too much. HOWEVER I would suggest you take the date and time as one field and actually store it as a datetime or datetime2 (you might already be doing this).


by the way, it's probably lucky you had syntax issues in your loop, because if you had at least one record in table1 then

while (select count(*) from Table1) > 0

would always be true and there was no way out of that loop.
LVL 69

Expert Comment

by:Scott Pletcher
ID: 40325806
You don't need to concatenate everything into a single column to make it a primary key value.

Just define the combination of the three columns as a PK:

ALTER TABLE dbo.Table1
ADD CONSTRAINT Table1__PK PRIMARY KEY ( Date, Time, code )

You're just wasting processing and disk space by concatenating existing columns and storing them again.

Featured Post

Linux Academy Android App Now Supports Chromecast

We have some fantastic news for our Android fans. We’re so excited to announce that the Linux Academy Android app is now available with Chromecast support. That’s right – simply download the latest update of the Linux Academy App and start casting your favorite course videos!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
A Stored Procedure in Microsoft SQL Server is a powerful feature that it can be used to execute the Data Manipulation Language (DML) or Data Definition Language (DDL). Depending on business requirements, a single Stored Procedure can return differe…
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.
Suggested Courses

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question