Showing posts with label number. Show all posts
Showing posts with label number. Show all posts

Tuesday, March 27, 2012

Correct access to TempDB?

uff... I've another problem...
In this loop I've same ADO 2.7 error (number: -2147217865,
description: Invalid object name '#tabella_temp') at STEP 3:

'--STEP 1--
sSql = "IF OBJECT_ID('tempdb..#tabella') IS NOT NULL DROP TABLE
#tabella"
m_cn.Execute sSql, RowAff, adExecuteNoRecords

'--STEP 2--
sSql = "SELECT top 0 * INTO #tabella_temp FROM tabella"
m_cn.Execute sSql, RowAff, adExecuteNoRecords

'STEP --READ DATA--
sSql = "SELECT IdRow from TabellaIn"
rs.Open sSql, m_cn, adOpenForwardOnly, adLockReadOnly

Do While Not rs.EOF
'--STEP 3--
sSql = "insert into #tabella_temp (row) values (" & rs("IdRow") &
")"
m_cn.Execute sSql, RowAff, adExecuteNoRecords
rs.MoveNext
Loop
rs.CLose

why , why, why?zMatteo (origma@.edpsistem.it) writes:
> uff... I've another problem...
> In this loop I've same ADO 2.7 error (number: -2147217865,
> description: Invalid object name '#tabella_temp') at STEP 3:
> '--STEP 1--
> sSql = "IF OBJECT_ID('tempdb..#tabella') IS NOT NULL DROP TABLE
> #tabella"
> m_cn.Execute sSql, RowAff, adExecuteNoRecords
> '--STEP 2--
> sSql = "SELECT top 0 * INTO #tabella_temp FROM tabella"
> m_cn.Execute sSql, RowAff, adExecuteNoRecords
> 'STEP --READ DATA--
> sSql = "SELECT IdRow from TabellaIn"
> rs.Open sSql, m_cn, adOpenForwardOnly, adLockReadOnly
> Do While Not rs.EOF
> '--STEP 3--
> sSql = "insert into #tabella_temp (row) values (" & rs("IdRow") &
> ")"
> m_cn.Execute sSql, RowAff, adExecuteNoRecords
> rs.MoveNext
> Loop
> rs.CLose
>
> why , why, why?

Seems to be the same problem again. Your connection is busy with getting
data from TabellaIn, so ADO opens second connection for you, and then
the temp table is not there.

Two ways to address this:

o Use a client-side cursor. (Connection.CursorLocation = adUseClient)
o Explicitly use two connection, ond for data in and one for
data out.

(Actually I am not entirely sure that using a client-side cursor is
enough. But it's a good thing anyway.)

And of course, if all you do is copy data, it is much more effective
to do it down in SQL Server and not get the data forth and back over
the network.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

Sunday, March 25, 2012

Copying tables, finding number of columns in a table, & size of data in selected colum

I'm trying to figure out how to do a few things in MS SQL Server but can't
Google up what I need or find it in the docs that I have.
1) How do you simply copy a table. I just want table A copied with all
its indexes and data in the same database as table A_copy.
2) I know how to figure out how many rows a table has, how do you figure
out how many columns?
3) Where does it say how large in terms of disk space (data) a table is?
4) Can you determine how large in terms of disk space only selected
columns within a table are?
[ Sugapablo ]
[ http://www.sugapablo.net <--personal | http://www.sugapablo.com <--music ]
[ http://www.2ra.org <--political | http://www.subuse.net <--discuss ]
> 1) How do you simply copy a table. I just want table A copied with all
> its indexes and data in the same database as table A_copy.
SELECT * INTO A_copy
FROM A
Note: PK and FK and any indexed columns will migrate their data, but the
PK, FK and indexes themselves will not be recreated. You will have to do
that yourself.

> 2) I know how to figure out how many rows a table has, how do you figure
> out how many columns?
Take a look at the INFORMATION_SCHEMA views.
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '<tablename>'

> 3) Where does it say how large in terms of disk space (data) a table is?
You can start with sp_spaceused 'objname'
EXEC sp_spaceused 'SomeTable'

> 4) Can you determine how large in terms of disk space only selected
> columns within a table are?
>
Not easily. You would need to get the width of the column (average width
for variable length columns) and multiply that by the number of rows in the
table. There are other factors to include, however, this should get you
reasonably close.
Rick Sawtell
MCT, MCSD, MCDBA
|||Hi,
I'm trying to figure out how to do a few things in MS SQL Server but can't
Google up what I need or find it in the docs that I have.
1) How do you simply copy a table. I just want table A copied with all its
indexes and data in the same database as table A_copy.
Generate Script with dependant objects using enterprise manager, execute
that in destination
database and use DTS to transfer the data.
2) I know how to figure out how many rows a table has, how do you figure out
how many columns?
select count(*) from syscolumns where object_name(id)='table_name'
or
Query the same on INFORMATION_SCHEMA.COLUMNS VIEW.
3) Where does it say how large in terms of disk space (data) a table is?
sp_spaceused <table_name>
4) Can you determine how large in terms of disk space only selected columns
within a table are?
You have to manually calculate based on usage and alloctions for each field.
Thanks
Hari
SQL Server MVP
"Sugapablo" <russ@.REMOVEsugapablo.com> wrote in message
news:pan.2005.05.23.16.12.37.486877@.REMOVEsugapabl o.com...
> I'm trying to figure out how to do a few things in MS SQL Server but can't
> Google up what I need or find it in the docs that I have.
> 1) How do you simply copy a table. I just want table A copied with all
> its indexes and data in the same database as table A_copy.
> 2) I know how to figure out how many rows a table has, how do you figure
> out how many columns?
> 3) Where does it say how large in terms of disk space (data) a table is?
> 4) Can you determine how large in terms of disk space only selected
> columns within a table are?
>
> --
> [
> ]
> [ http://www.sugapablo.net <--personal | http://www.sugapablo.com
> <--music ]
> [ http://www.2ra.org <--political | http://www.subuse.net
> <--discuss ]
>

Copying tables, finding number of columns in a table, & size of data in selected c

I'm trying to figure out how to do a few things in MS SQL Server but can't
Google up what I need or find it in the docs that I have.
1) How do you simply copy a table. I just want table A copied with all
its indexes and data in the same database as table A_copy.
2) I know how to figure out how many rows a table has, how do you figure
out how many columns?
3) Where does it say how large in terms of disk space (data) a table is?
4) Can you determine how large in terms of disk space only selected
columns within a table are?
[ Sugapablo
]
[ http://www.sugapablo.net <--personal | http://www.sugapablo.com <--mu
sic ]
[ http://www.2ra.org <--political | http://www.subuse.net <--di
scuss ]> 1) How do you simply copy a table. I just want table A copied with all
> its indexes and data in the same database as table A_copy.
SELECT * INTO A_copy
FROM A
Note: PK and FK and any indexed columns will migrate their data, but the
PK, FK and indexes themselves will not be recreated. You will have to do
that yourself.

> 2) I know how to figure out how many rows a table has, how do you figure
> out how many columns?
Take a look at the INFORMATION_SCHEMA views.
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '<tablename>'

> 3) Where does it say how large in terms of disk space (data) a table is?
You can start with sp_spaceused 'objname'
EXEC sp_spaceused 'SomeTable'

> 4) Can you determine how large in terms of disk space only selected
> columns within a table are?
>
Not easily. You would need to get the width of the column (average width
for variable length columns) and multiply that by the number of rows in the
table. There are other factors to include, however, this should get you
reasonably close.
Rick Sawtell
MCT, MCSD, MCDBA|||Hi,
I'm trying to figure out how to do a few things in MS SQL Server but can't
Google up what I need or find it in the docs that I have.
1) How do you simply copy a table. I just want table A copied with all its
indexes and data in the same database as table A_copy.
Generate Script with dependant objects using enterprise manager, execute
that in destination
database and use DTS to transfer the data.
2) I know how to figure out how many rows a table has, how do you figure out
how many columns?
select count(*) from syscolumns where object_name(id)='table_name'
or
Query the same on INFORMATION_SCHEMA.COLUMNS VIEW.
3) Where does it say how large in terms of disk space (data) a table is?
sp_spaceused <table_name>
4) Can you determine how large in terms of disk space only selected columns
within a table are?
You have to manually calculate based on usage and alloctions for each field.
Thanks
Hari
SQL Server MVP
"Sugapablo" <russ@.REMOVEsugapablo.com> wrote in message
news:pan.2005.05.23.16.12.37.486877@.REMOVEsugapablo.com...
> I'm trying to figure out how to do a few things in MS SQL Server but can't
> Google up what I need or find it in the docs that I have.
> 1) How do you simply copy a table. I just want table A copied with all
> its indexes and data in the same database as table A_copy.
> 2) I know how to figure out how many rows a table has, how do you figure
> out how many columns?
> 3) Where does it say how large in terms of disk space (data) a table is?
> 4) Can you determine how large in terms of disk space only selected
> columns within a table are?
>
> --
> [
> ]
> [ http://www.sugapablo.net <--personal | http://www.sugapablo.com
> <--music ]
> [ http://www.2ra.org <--political | http://www.subuse.net
> <--discuss ]
>

Tuesday, March 20, 2012

copying server objects

I want to copy a database from one server to another. I'm happy about
how to do this but also want to copy a number of DTS packages, jobs and
alerts that relate to this database. Is there any way that I can copy
them or will I need to create them again on the new server.

Many Thanks

Laurence BreezeYou can copy DTS packages by opening up the current package and choosing
"Package/Save As..." from the menu bar. Be careful to make sure your
database references within the DTS package are still appropriate on the
new server.

Both jobs and alerts can be scripted and that script executed on the new
server - right click the jobs or alerts and choose "All Tasks/Generate
SQL Script...". More than one job or alert can be selected at a time if
you desire.

Good luck,
Tony Sebion

"Laurence Breeze" <i.l.breeze@.open.ac.uk> wrote in message
news:433D4E58.2050802@.open.ac.uk:

> I want to copy a database from one server to another. I'm happy about
> how to do this but also want to copy a number of DTS packages, jobs and
> alerts that relate to this database. Is there any way that I can copy
> them or will I need to create them again on the new server.
> Many Thanks
> Laurence Breeze|||Hi

You may want to read
http://support.microsoft.com/defaul...b;en-us;Q314546

John

"Laurence Breeze" <i.l.breeze@.open.ac.uk> wrote in message
news:433D4E58.2050802@.open.ac.uk...
>I want to copy a database from one server to another. I'm happy about how
>to do this but also want to copy a number of DTS packages, jobs and alerts
>that relate to this database. Is there any way that I can copy them or
>will I need to create them again on the new server.
> Many Thanks
> Laurence Breezesql

Thursday, March 8, 2012

Copying data from on database to another

Hi,
I currently have 3 databases, master_database, database_one and
database_two. Both database_one and database_two contain a number of
different tables recording different information, some of these tables
need to be backed up to the master_database. Within the master_database
is a table that contains a list of tables that need to be updated.
Basically the master_database contains all the information where
database_one and database_two periodically delete the oldest rows so
that the table in the two database are not too large. So far I've
created a store proceedure in the master_database that goes through the
list of tables and if the tables is not present in the master_database
then it is created and populated with the data in the original table
(be it in either database_one or database_two). However I'm having
difficulty with if the table is present in the master_database on how
to update it, only the rows that are not present in the master_database
need to be copied. I currently have:
insert into table1 select * from database_one.dbo.table1
where database_one.dbo.table1.timestamp >(select max(timestamp) from
table1)
however the problem with this is that it doesnt update all the rows and
it looks at timestamp and depending on the table then there are
differet primary keys.
Any advise on how to get arround this would be much appreciated.
Thanks
Simon
Read up on replication in Books online. That can do everything you have
described.
Jacco Schalkwijk
SQL Server MVP
"accyboy1981" <accyboy1981@.gmail.com> wrote in message
news:1128431426.829767.109970@.o13g2000cwo.googlegr oups.com...
> Hi,
> I currently have 3 databases, master_database, database_one and
> database_two. Both database_one and database_two contain a number of
> different tables recording different information, some of these tables
> need to be backed up to the master_database. Within the master_database
> is a table that contains a list of tables that need to be updated.
> Basically the master_database contains all the information where
> database_one and database_two periodically delete the oldest rows so
> that the table in the two database are not too large. So far I've
> created a store proceedure in the master_database that goes through the
> list of tables and if the tables is not present in the master_database
> then it is created and populated with the data in the original table
> (be it in either database_one or database_two). However I'm having
> difficulty with if the table is present in the master_database on how
> to update it, only the rows that are not present in the master_database
> need to be copied. I currently have:
> insert into table1 select * from database_one.dbo.table1
> where database_one.dbo.table1.timestamp >(select max(timestamp) from
> table1)
> however the problem with this is that it doesnt update all the rows and
> it looks at timestamp and depending on the table then there are
> differet primary keys.
> Any advise on how to get arround this would be much appreciated.
> Thanks
> Simon
>
|||Hi,
I know that its possible to do what I'm asking through replication but
I want to use a store procedure as its going to run every hour to
update the master_database. Any ideas on how it can be done in store
procedures?
Thanks
Simon
|||What are the specific reasons to use a stored procedure? You can schedule
replication.
Jacco Schalkwijk
SQL Server MVP
"accyboy1981" <accyboy1981@.gmail.com> wrote in message
news:1128432063.229252.248410@.z14g2000cwz.googlegr oups.com...
> Hi,
> I know that its possible to do what I'm asking through replication but
> I want to use a store procedure as its going to run every hour to
> update the master_database. Any ideas on how it can be done in store
> procedures?
> Thanks
> Simon
>
|||Hi,
The reasoning is that my boss wants it in a store procedure and not as
replication. From what I've read I would choose replication but in the
current situation I am unable to do so.
Simon

Copying data from on database to another

Hi,
I currently have 3 databases, master_database, database_one and
database_two. Both database_one and database_two contain a number of
different tables recording different information, some of these tables
need to be backed up to the master_database. Within the master_database
is a table that contains a list of tables that need to be updated.
Basically the master_database contains all the information where
database_one and database_two periodically delete the oldest rows so
that the table in the two database are not too large. So far I've
created a store proceedure in the master_database that goes through the
list of tables and if the tables is not present in the master_database
then it is created and populated with the data in the original table
(be it in either database_one or database_two). However I'm having
difficulty with if the table is present in the master_database on how
to update it, only the rows that are not present in the master_database
need to be copied. I currently have:
insert into table1 select * from database_one.dbo.table1
where database_one.dbo.table1.timestamp >(select max(timestamp) from
table1)
however the problem with this is that it doesnt update all the rows and
it looks at timestamp and depending on the table then there are
differet primary keys.
Any advise on how to get arround this would be much appreciated.
Thanks
SimonRead up on replication in Books online. That can do everything you have
described.
Jacco Schalkwijk
SQL Server MVP
"accyboy1981" <accyboy1981@.gmail.com> wrote in message
news:1128431426.829767.109970@.o13g2000cwo.googlegroups.com...
> Hi,
> I currently have 3 databases, master_database, database_one and
> database_two. Both database_one and database_two contain a number of
> different tables recording different information, some of these tables
> need to be backed up to the master_database. Within the master_database
> is a table that contains a list of tables that need to be updated.
> Basically the master_database contains all the information where
> database_one and database_two periodically delete the oldest rows so
> that the table in the two database are not too large. So far I've
> created a store proceedure in the master_database that goes through the
> list of tables and if the tables is not present in the master_database
> then it is created and populated with the data in the original table
> (be it in either database_one or database_two). However I'm having
> difficulty with if the table is present in the master_database on how
> to update it, only the rows that are not present in the master_database
> need to be copied. I currently have:
> insert into table1 select * from database_one.dbo.table1
> where database_one.dbo.table1.timestamp >(select max(timestamp) from
> table1)
> however the problem with this is that it doesnt update all the rows and
> it looks at timestamp and depending on the table then there are
> differet primary keys.
> Any advise on how to get arround this would be much appreciated.
> Thanks
> Simon
>|||Hi,
I know that its possible to do what I'm asking through replication but
I want to use a store procedure as its going to run every hour to
update the master_database. Any ideas on how it can be done in store
procedures?
Thanks
Simon|||What are the specific reasons to use a stored procedure? You can schedule
replication.
Jacco Schalkwijk
SQL Server MVP
"accyboy1981" <accyboy1981@.gmail.com> wrote in message
news:1128432063.229252.248410@.z14g2000cwz.googlegroups.com...
> Hi,
> I know that its possible to do what I'm asking through replication but
> I want to use a store procedure as its going to run every hour to
> update the master_database. Any ideas on how it can be done in store
> procedures?
> Thanks
> Simon
>|||Hi,
The reasoning is that my boss wants it in a store procedure and not as
replication. From what I've read I would choose replication but in the
current situation I am unable to do so.
Simon

Copying data from on database to another

Hi,
I currently have 3 databases, master_database, database_one and
database_two. Both database_one and database_two contain a number of
different tables recording different information, some of these tables
need to be backed up to the master_database. Within the master_database
is a table that contains a list of tables that need to be updated.
Basically the master_database contains all the information where
database_one and database_two periodically delete the oldest rows so
that the table in the two database are not too large. So far I've
created a store proceedure in the master_database that goes through the
list of tables and if the tables is not present in the master_database
then it is created and populated with the data in the original table
(be it in either database_one or database_two). However I'm having
difficulty with if the table is present in the master_database on how
to update it, only the rows that are not present in the master_database
need to be copied. I currently have:
insert into table1 select * from database_one.dbo.table1
where database_one.dbo.table1.timestamp >(select max(timestamp) from
table1)
however the problem with this is that it doesnt update all the rows and
it looks at timestamp and depending on the table then there are
differet primary keys.
Any advise on how to get arround this would be much appreciated.
Thanks
SimonRead up on replication in Books online. That can do everything you have
described.
--
Jacco Schalkwijk
SQL Server MVP
"accyboy1981" <accyboy1981@.gmail.com> wrote in message
news:1128431426.829767.109970@.o13g2000cwo.googlegroups.com...
> Hi,
> I currently have 3 databases, master_database, database_one and
> database_two. Both database_one and database_two contain a number of
> different tables recording different information, some of these tables
> need to be backed up to the master_database. Within the master_database
> is a table that contains a list of tables that need to be updated.
> Basically the master_database contains all the information where
> database_one and database_two periodically delete the oldest rows so
> that the table in the two database are not too large. So far I've
> created a store proceedure in the master_database that goes through the
> list of tables and if the tables is not present in the master_database
> then it is created and populated with the data in the original table
> (be it in either database_one or database_two). However I'm having
> difficulty with if the table is present in the master_database on how
> to update it, only the rows that are not present in the master_database
> need to be copied. I currently have:
> insert into table1 select * from database_one.dbo.table1
> where database_one.dbo.table1.timestamp >(select max(timestamp) from
> table1)
> however the problem with this is that it doesnt update all the rows and
> it looks at timestamp and depending on the table then there are
> differet primary keys.
> Any advise on how to get arround this would be much appreciated.
> Thanks
> Simon
>|||Hi,
I know that its possible to do what I'm asking through replication but
I want to use a store procedure as its going to run every hour to
update the master_database. Any ideas on how it can be done in store
procedures?
Thanks
Simon|||What are the specific reasons to use a stored procedure? You can schedule
replication.
--
Jacco Schalkwijk
SQL Server MVP
"accyboy1981" <accyboy1981@.gmail.com> wrote in message
news:1128432063.229252.248410@.z14g2000cwz.googlegroups.com...
> Hi,
> I know that its possible to do what I'm asking through replication but
> I want to use a store procedure as its going to run every hour to
> update the master_database. Any ideas on how it can be done in store
> procedures?
> Thanks
> Simon
>|||Hi,
The reasoning is that my boss wants it in a store procedure and not as
replication. From what I've read I would choose replication but in the
current situation I am unable to do so.
Simon

Copying data across rows

I have one table where I am trying to copy a number from one field
in one row into another field in another row based on two conditions.
More specifically, I need to copy the number from column DIFF for
group LY into column DIFF_CO for group L+. This is what I would like
to do:
UPDATE mytable
SET diff_co = (SELECT diff FROM mytable WHERE group=LY and name=name1)
WHERE name=name1 and group=L+
... so that my end result looks like this:
GROUP NAME DIFF DIFF_CO
LY Name1 9.9
L+ Name1 10.2 9.9
Where I am running into difficulty is that the select statement returns
242 results, and thus the "Subquery returned more than 1 value" error.
Any suggestions on how I can do this?
Hope that following can help you:
1. Verify how many rows are returned by following query:
SELECT distinct diff FROM mytable WHERE group=LY and name=name1
2. If the above query returns only 1 row, then use the following query to
'copy data across rows':
UPDATE mytable
SET diff_co = (SELECT distinct diff FROM mytable WHERE group=LY and
name=name1)
WHERE name=name1 and group=L+
"nicole" wrote:

> I have one table where I am trying to copy a number from one field
> in one row into another field in another row based on two conditions.
> More specifically, I need to copy the number from column DIFF for
> group LY into column DIFF_CO for group L+. This is what I would like
> to do:
> UPDATE mytable
> SET diff_co = (SELECT diff FROM mytable WHERE group=LY and name=name1)
> WHERE name=name1 and group=L+
>
> ... so that my end result looks like this:
> GROUP NAME DIFF DIFF_CO
> LY Name1 9.9
> L+ Name1 10.2 9.9
>
> Where I am running into difficulty is that the select statement returns
> 242 results, and thus the "Subquery returned more than 1 value" error.
> Any suggestions on how I can do this?
|||> Hope that following can help you:
Thanks for the reply!!

> 1. Verify how many rows are returned by following query:
> SELECT distinct diff FROM mytable WHERE group=LY and name=name1
> 2. If the above query returns only 1 row, then use the following query to
> 'copy data across rows':
Unfortunately, the distinct query returns multiple rows.
Any other suggestions?
|||since it gives multiple diff values you have to choose which diff value
you want to use for update
You can do this by either using max, min or top 1 in the subquery.
UPDATE mytable
SET diff_co = (SELECT max(diff) FROM mytable WHERE group=LY and
name=name1)
WHERE name=name1 and group=L+
or
UPDATE mytable
SET diff_co = (SELECT min(diff) FROM mytable WHERE group=LY and
name=name1)
WHERE name=name1 and group=L+
or
UPDATE mytable
SET diff_co = (SELECT top 1 (diff) FROM mytable WHERE group=LY and
name=name1)
WHERE name=name1 and group=L+

Copying data across rows

I have one table where I am trying to copy a number from one field
in one row into another field in another row based on two conditions.
More specifically, I need to copy the number from column DIFF for
group LY into column DIFF_CO for group L+. This is what I would like
to do:
UPDATE mytable
SET diff_co = (SELECT diff FROM mytable WHERE group=LY and name=name1)
WHERE name=name1 and group=L+
... so that my end result looks like this:
GROUP NAME DIFF DIFF_CO
LY Name1 9.9
L+ Name1 10.2 9.9
Where I am running into difficulty is that the select statement returns
242 results, and thus the "Subquery returned more than 1 value" error.
Any suggestions on how I can do this?Hope that following can help you:
1. Verify how many rows are returned by following query:
SELECT distinct diff FROM mytable WHERE group=LY and name=name1
2. If the above query returns only 1 row, then use the following query to
'copy data across rows':
UPDATE mytable
SET diff_co = (SELECT distinct diff FROM mytable WHERE group=LY and
name=name1)
WHERE name=name1 and group=L+
"nicole" wrote:

> I have one table where I am trying to copy a number from one field
> in one row into another field in another row based on two conditions.
> More specifically, I need to copy the number from column DIFF for
> group LY into column DIFF_CO for group L+. This is what I would like
> to do:
> UPDATE mytable
> SET diff_co = (SELECT diff FROM mytable WHERE group=LY and name=name1)
> WHERE name=name1 and group=L+
>
> ... so that my end result looks like this:
> GROUP NAME DIFF DIFF_CO
> LY Name1 9.9
> L+ Name1 10.2 9.9
>
> Where I am running into difficulty is that the select statement returns
> 242 results, and thus the "Subquery returned more than 1 value" error.
> Any suggestions on how I can do this?|||> Hope that following can help you:
Thanks for the reply!!

> 1. Verify how many rows are returned by following query:
> SELECT distinct diff FROM mytable WHERE group=LY and name=name1
> 2. If the above query returns only 1 row, then use the following query to
> 'copy data across rows':
Unfortunately, the distinct query returns multiple rows.
Any other suggestions?|||since it gives multiple diff values you have to choose which diff value
you want to use for update
You can do this by either using max, min or top 1 in the subquery.
UPDATE mytable
SET diff_co = (SELECT max(diff) FROM mytable WHERE group=LY and
name=name1)
WHERE name=name1 and group=L+
or
UPDATE mytable
SET diff_co = (SELECT min(diff) FROM mytable WHERE group=LY and
name=name1)
WHERE name=name1 and group=L+
or
UPDATE mytable
SET diff_co = (SELECT top 1 (diff) FROM mytable WHERE group=LY and
name=name1)
WHERE name=name1 and group=L+

Copying data across rows

I have one table where I am trying to copy a number from one field
in one row into another field in another row based on two conditions.
More specifically, I need to copy the number from column DIFF for
group LY into column DIFF_CO for group L+. This is what I would like
to do:
UPDATE mytable
SET diff_co = (SELECT diff FROM mytable WHERE group=LY and name=name1)
WHERE name=name1 and group=L+
... so that my end result looks like this:
GROUP NAME DIFF DIFF_CO
LY Name1 9.9
L+ Name1 10.2 9.9
Where I am running into difficulty is that the select statement returns
242 results, and thus the "Subquery returned more than 1 value" error.
Any suggestions on how I can do this?Hope that following can help you:
1. Verify how many rows are returned by following query:
SELECT distinct diff FROM mytable WHERE group=LY and name=name1
2. If the above query returns only 1 row, then use the following query to
'copy data across rows':
UPDATE mytable
SET diff_co = (SELECT distinct diff FROM mytable WHERE group=LY and
name=name1)
WHERE name=name1 and group=L+
"nicole" wrote:
> I have one table where I am trying to copy a number from one field
> in one row into another field in another row based on two conditions.
> More specifically, I need to copy the number from column DIFF for
> group LY into column DIFF_CO for group L+. This is what I would like
> to do:
> UPDATE mytable
> SET diff_co = (SELECT diff FROM mytable WHERE group=LY and name=name1)
> WHERE name=name1 and group=L+
>
> ... so that my end result looks like this:
> GROUP NAME DIFF DIFF_CO
> LY Name1 9.9
> L+ Name1 10.2 9.9
>
> Where I am running into difficulty is that the select statement returns
> 242 results, and thus the "Subquery returned more than 1 value" error.
> Any suggestions on how I can do this?|||> Hope that following can help you:
Thanks for the reply!!
> 1. Verify how many rows are returned by following query:
> SELECT distinct diff FROM mytable WHERE group=LY and name=name1
> 2. If the above query returns only 1 row, then use the following query to
> 'copy data across rows':
Unfortunately, the distinct query returns multiple rows.
Any other suggestions?|||since it gives multiple diff values you have to choose which diff value
you want to use for update
You can do this by either using max, min or top 1 in the subquery.
UPDATE mytable
SET diff_co = (SELECT max(diff) FROM mytable WHERE group=LY and
name=name1)
WHERE name=name1 and group=L+
or
UPDATE mytable
SET diff_co = (SELECT min(diff) FROM mytable WHERE group=LY and
name=name1)
WHERE name=name1 and group=L+
or
UPDATE mytable
SET diff_co = (SELECT top 1 (diff) FROM mytable WHERE group=LY and
name=name1)
WHERE name=name1 and group=L+

Friday, February 24, 2012

copy two table

hi,

How copy two table between two database?

copy 1 table1 to 2 table2

1 - cursor number,
2 - cursor number,
table1 - sourse table
table2 - destination table

Jaromi"ja" <jaromi111@.poczta.onet.pl> ???/???? ? ???? ???:
news:1etlgtor6kjsh.bx223caeyi5p$.dlg@.40tude.net...
> hi,
> How copy two table between two database?
> copy 1 table1 to 2 table2
> 1 - cursor number,
> 2 - cursor number,
> table1 - sourse table
> table2 - destination table
> Jaromi

Right click on table in EM -> all tasks -> export data...|||On Sun, 15 Aug 2004 20:42:08 +0200, ja wrote:

>hi,
>How copy two table between two database?
>copy 1 table1 to 2 table2
>1 - cursor number,
>2 - cursor number,
>table1 - sourse table
>table2 - destination table
>Jaromi

Hi Jaromi,

Probably something like this:

INSERT table2 (column1, column2, ...)
SELECT column1, column2, ...
FROM table1

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)

Sunday, February 19, 2012

Copy Table in same database

I'm using partitions in my project to age data that's older than some predetermined number of days. Normal deletion of the data takes too long, but the following sequence of operations seems to work well when testing with raw sql queries:

    Split (to create a new partition for new data) Create (a new temporary table to hold the oldest partition's data) Switch (to move the oldest partition's data into the new temporary table) Merge (to combine the oldest two partitions, "removing" the oldest one in the process) Drop (to drop the temporary table and all the old data that we don't want anymore)

My current problem arises at step 2, "Create." The precise column/index/etc layout of the data being aged is not be known/hardcoded into my program. I've been trying to use SMO to create a copy of an existing table into the same database with a new name, but I've been failing miserably. It may include a varbinary(max), e.g., and the "max" part doesn't seem to be exposed by Smo.Column.Datatype.

Is there a way to dynamically create a copy of a table that already exists inside the same database, changing only the name and without bringing along the table's data?

Or should I smack my DBA upside the head and tell him to put in some extra temporary tables that I can just truncate instead of making me create them dynamically?

One technique is to use a Select Into:

Select * Into myNewTableName From myOldTableName Where 1=2 -- usually returns no records ;)|||Sure, I could SELECT INTO, but then what's the point of SMO? Isn't the goal, here, to avoid manually building my own query?|||

The point of SMO is that it provides an object library for you to write code to make your management of SQL Server easier for you. If something can be easily accomplished with Transact-SQL, then why not use it? It's not about platform evangelism, it's about making your job easier.

That being said, this code will bring in the HumanResources.Employee table from the AdventureWorks database and replicate it into a new table called HumanResources.NewEmp:

Dim srv As Server
Dim srvConn As ServerConnection
srv = New Server("MyServer")
srvConn = srv.ConnectionContext
srvConn.LoginSecure = True

Dim db As Database
db = srv.Databases("AdventureWorks")

Dim tblExisting As Table
Dim tblNew As Table

tblExisting = db.Tables.Item("Employee", "HumanResources")
tblNew = New Table(db, "NewEmp", "HumanResources")
Dim colExistColumn As ColumnCollection
Dim clmExist As Column
colExistColumn = tblExisting.Columns
For Each clmExist In colExistColumn
Dim clmNew As Column
clmNew = New Column(tblNew, clmExist.Name)
clmNew.DataType = clmExist.DataType
clmNew.Nullable = clmExist.Nullable
tblNew.Columns.Add(clmNew)
Next
tblNew.Create()

Good luck.

|||

Thanks for the info, Allen, but I've already gone down that road. Don't forget an index loop that goes something like:

foreach (Index idx in tblOld){
String idxName = idx.Name + "_newTable"; // Or whatever, not important here
tblNew.Indexes.Add(new Index(tblNew, idxName));
tblNew.Indexes[idxName].IsClustered = idx.IsClustered;
tblNew.Indexes[idxName].IndexKeyType = idx.IndexKeyType;
tblNew.Indexes[idxName].IgnoreDuplicateKeys = idx.IgnoreDuplicateKeys;
tblNew.Indexes[idxName].IsUnique = idx.IsUnique;
foreach (IndexedColumn col in idx.IndexedColumns){
tblNew.Indexes[idxName].IndexedColumns.Add(new IndexedColumn(tblNew.Indexes[idxName], col.Name));
}
}

Recall that the tables have to be sufficiently compatible for me to switch a partition from the original into the temporary table. Creating just a table with the same column types doesn't cut it. The code sample you provide (which is nearly identical to what I wrote in my own code as well) also won't deal properly with all column data types. Try that code on a table with a type of varbinary(max), e.g. The temporary table that's created will be of type varbinary(1).

Unhandled Exception: Microsoft.SqlServer.Management.Smo.FailedOperationException: Switch partition failed for Table 'dbo.tblOld'. > Microsoft.SqlServer.Management.Common.ExecutionFailureException: An exception occurred while executing a Transact-SQL statement or batch. > System.Data.SqlClient.SqlException: ALTER TABLE SWITCH statement failed because column 'col' has data type varbinary(max) in source table 'DbName.dbo.tblOld' which is different from its type varbinary(1) in target table 'DbName.dbo.tblNew'.

Bang. I'm dead. Do I have to create more explicit special-cased logic to handle var* types? That'd be silly.

If I have to jump through that many hoops to perform a copy operation, it tells me that copying via this technique isn't supported by the SMO libraries. I'm essentially trying to perform a manual deep-copy via a public interface. Perhaps I need to subclass the table type? Create a class "CopyableTable"? I don't think the protected methods/members will provide sufficient support for what I want either, though.

If something can be easily accomplished with T-SQL, why not use it? Company policies that have been put into place to mitigate the possibility SQL Injection would be one reason. SQL strings in the source code raise big red flags, and SMO should be able to handle this use-case.

|||

Sorry, Greg, I forgot to mention that in SMO you set the column to use varbinary(MAX) by setting the column.DataType.MaximumLength = -1

I'll be doing a demo of that in my presentation at PASS in two weeks. Your point on company policies is well taken, and I had a hunch the issue was something along those lines. I don't know why the MaximumLength property isn't carried forward to the new table - it's probably a bug, but knowing how the MAX datatype is internally coded (and I haven't found documentation about this, I just discovered it by poking around) can help resolve the problems you're facing.

Hope that helps.

|||

Thanks, Allen. I haven't tried that, so I'll give it a go and see what happens.

I agree, it's weird that MaximumLength isn't carried through.

|||

First try:

colNew.DataType.MaximumLength = colOld.DataType.MaximumLength;

Failed.

Second try:

if(colOld.DataType.MaximumLength == -1){
colNew.DataType.MaximumLength = -1;
}

Failed.

Third try:

if(colOld.DataType.MaximumLength == -1){
colNew.DataType.MaximumLength = 5;
}

Failed to set it to 5. The created table still has a varbinary length as 1. At this point I revisited the DataType interface, suspecting that these var* types must be special somehow, and I noticed some promising possibilities.

Fourth try:

if(colOld.DataType.Name == "varbinary"){
if(colOld.DataType.MaximumLength == -1)
colNew.DataType = DataType.VarBinaryMax;
else
colNew.DataType = DataType.VarBinary(colOld.DataType.MaximumLength);
}

No luck. Grrrr. I really expected that last one to work. If I replace VarBinaryMax with VarBinary(5), the tblNew.Create() method will kick out a varbinary(5). Which brings us back to your suggestion:

if(colOld.DataType.Name == "varbinary"){
if(colOld.DataType.MaximumLength == -1)
colNew.DataType = DataType.VarBinary(-1);
else
colNew.DataType = DataType.VarBinary(colOld.DataType.MaximumLength);
}

Which works. http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=662296&SiteID=17 had similar info.

Thanks again, Allen.

|||

Good technique.

I must copy also Dependencies of Stored Procedure.

Do you know anyidea ?

Copy Table in same database

I'm using partitions in my project to age data that's older than some predetermined number of days. Normal deletion of the data takes too long, but the following sequence of operations seems to work well when testing with raw sql queries:

    Split (to create a new partition for new data)

    Create (a new temporary table to hold the oldest partition's data)

    Switch (to move the oldest partition's data into the new temporary table)

    Merge (to combine the oldest two partitions, "removing" the oldest one in the process)

    Drop (to drop the temporary table and all the old data that we don't want anymore)

My current problem arises at step 2, "Create." The precise column/index/etc layout of the data being aged is not be known/hardcoded into my program. I've been trying to use SMO to create a copy of an existing table into the same database with a new name, but I've been failing miserably. It may include a varbinary(max), e.g., and the "max" part doesn't seem to be exposed by Smo.Column.Datatype.

Is there a way to dynamically create a copy of a table that already exists inside the same database, changing only the name and without bringing along the table's data?

Or should I smack my DBA upside the head and tell him to put in some extra temporary tables that I can just truncate instead of making me create them dynamically?

One technique is to use a Select Into:

Select *

Into myNewTableName

From myOldTableName

Where 1=2 -- usually returns no records ;)|||Sure, I could SELECT INTO, but then what's the point of SMO? Isn't the goal, here, to avoid manually building my own query?|||

The point of SMO is that it provides an object library for you to write code to make your management of SQL Server easier for you. If something can be easily accomplished with Transact-SQL, then why not use it? It's not about platform evangelism, it's about making your job easier.

That being said, this code will bring in the HumanResources.Employee table from the AdventureWorks database and replicate it into a new table called HumanResources.NewEmp:

Dim srv As Server
Dim srvConn As ServerConnection
srv = New Server("MyServer")
srvConn = srv.ConnectionContext
srvConn.LoginSecure = True

Dim db As Database
db = srv.Databases("AdventureWorks")

Dim tblExisting As Table
Dim tblNew As Table

tblExisting = db.Tables.Item("Employee", "HumanResources")
tblNew = New Table(db, "NewEmp", "HumanResources")
Dim colExistColumn As ColumnCollection
Dim clmExist As Column
colExistColumn = tblExisting.Columns
For Each clmExist In colExistColumn
Dim clmNew As Column
clmNew = New Column(tblNew, clmExist.Name)
clmNew.DataType = clmExist.DataType
clmNew.Nullable = clmExist.Nullable
tblNew.Columns.Add(clmNew)
Next
tblNew.Create()

Good luck.

|||

Thanks for the info, Allen, but I've already gone down that road. Don't forget an index loop that goes something like:

foreach (Index idx in tblOld){
String idxName = idx.Name + "_newTable"; // Or whatever, not important here
tblNew.Indexes.Add(new Index(tblNew, idxName));
tblNew.Indexes[idxName].IsClustered = idx.IsClustered;
tblNew.Indexes[idxName].IndexKeyType = idx.IndexKeyType;
tblNew.Indexes[idxName].IgnoreDuplicateKeys = idx.IgnoreDuplicateKeys;
tblNew.Indexes[idxName].IsUnique = idx.IsUnique;
foreach (IndexedColumn col in idx.IndexedColumns){
tblNew.Indexes[idxName].IndexedColumns.Add(new IndexedColumn(tblNew.Indexes[idxName], col.Name));
}
}

Recall that the tables have to be sufficiently compatible for me to switch a partition from the original into the temporary table. Creating just a table with the same column types doesn't cut it. The code sample you provide (which is nearly identical to what I wrote in my own code as well) also won't deal properly with all column data types. Try that code on a table with a type of varbinary(max), e.g. The temporary table that's created will be of type varbinary(1).

Unhandled Exception: Microsoft.SqlServer.Management.Smo.FailedOperationException: Switch partition failed for Table 'dbo.tblOld'. > Microsoft.SqlServer.Management.Common.ExecutionFailureException: An exception occurred while executing a Transact-SQL statement or batch. > System.Data.SqlClient.SqlException: ALTER TABLE SWITCH statement failed because column 'col' has data type varbinary(max) in source table 'DbName.dbo.tblOld' which is different from its type varbinary(1) in target table 'DbName.dbo.tblNew'.

Bang. I'm dead. Do I have to create more explicit special-cased logic to handle var* types? That'd be silly.

If I have to jump through that many hoops to perform a copy operation, it tells me that copying via this technique isn't supported by the SMO libraries. I'm essentially trying to perform a manual deep-copy via a public interface. Perhaps I need to subclass the table type? Create a class "CopyableTable"? I don't think the protected methods/members will provide sufficient support for what I want either, though.

If something can be easily accomplished with T-SQL, why not use it? Company policies that have been put into place to mitigate the possibility SQL Injection would be one reason. SQL strings in the source code raise big red flags, and SMO should be able to handle this use-case.

|||

Sorry, Greg, I forgot to mention that in SMO you set the column to use varbinary(MAX) by setting the column.DataType.MaximumLength = -1

I'll be doing a demo of that in my presentation at PASS in two weeks. Your point on company policies is well taken, and I had a hunch the issue was something along those lines. I don't know why the MaximumLength property isn't carried forward to the new table - it's probably a bug, but knowing how the MAX datatype is internally coded (and I haven't found documentation about this, I just discovered it by poking around) can help resolve the problems you're facing.

Hope that helps.

|||

Thanks, Allen. I haven't tried that, so I'll give it a go and see what happens.

I agree, it's weird that MaximumLength isn't carried through.

|||

First try:

colNew.DataType.MaximumLength = colOld.DataType.MaximumLength;

Failed.

Second try:

if(colOld.DataType.MaximumLength == -1){
colNew.DataType.MaximumLength = -1;
}

Failed.

Third try:

if(colOld.DataType.MaximumLength == -1){
colNew.DataType.MaximumLength = 5;
}

Failed to set it to 5. The created table still has a varbinary length as 1. At this point I revisited the DataType interface, suspecting that these var* types must be special somehow, and I noticed some promising possibilities.

Fourth try:

if(colOld.DataType.Name == "varbinary"){
if(colOld.DataType.MaximumLength == -1)
colNew.DataType = DataType.VarBinaryMax;
else
colNew.DataType = DataType.VarBinary(colOld.DataType.MaximumLength);
}

No luck. Grrrr. I really expected that last one to work. If I replace VarBinaryMax with VarBinary(5), the tblNew.Create() method will kick out a varbinary(5). Which brings us back to your suggestion:

if(colOld.DataType.Name == "varbinary"){
if(colOld.DataType.MaximumLength == -1)
colNew.DataType = DataType.VarBinary(-1);
else
colNew.DataType = DataType.VarBinary(colOld.DataType.MaximumLength);
}

Which works. http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=662296&SiteID=17 had similar info.

Thanks again, Allen.

|||

Good technique.

I must copy also Dependencies of Stored Procedure.

Do you know anyidea ?