Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 139
  • Last Modified:

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

Hello,

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.

USE MyDB

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

	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
end

Open in new window


Thanks.
Ak
0
akohan
Asked:
akohan
2 Solutions
 
skillileaCommented:
Not sure exactly but...a CTE would run a lot faster.

Anyway here is a looping example.


DECLARE @t TABLE(
      RowID bigint identity (1,1)
      , TheDate datetime
      , TheCode varchar(50)
      )

DECLARE @x bigint

INSERT INTO @t      
      SELECT GETDATE(), NEWID()
      UNION
      SELECT GETDATE() +1 , NEWID()
      UNION
      SELECT GETDATE() + 2, NEWID()




SET @x = (SELECT MIN(RowID) FROM @t)
WHILE @x IS NOT NULL BEGIN

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


      SET @x = (SELECT MIN(RowID) FROM @t WHERE RowID > @x)
END
0
 
Russell FoxDatabase DeveloperCommented:
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:
DECLARE @Table1 TABLE(
	[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], ':', ''), '.', ''), '/', '')

SELECT *
FROM @Table1

Open in new window

0
 
akohanAuthor Commented:
Hi skillilea,

What is CTE?
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
akohanAuthor Commented:
Hi Russel,

Yes, I need uniqueness so should I change the column type to IDENTITY? then run your example?
0
 
skillileaCommented:
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.

sk
0
 
akohanAuthor Commented:
Ok, I understand what you are saying now but let me explain my situation.

Here:

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?

Thanks,
0
 
PortletPaulCommented:
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 */
SET
     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.
0
 
Scott PletcherSenior DBACommented:
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.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now