Friday, March 30, 2012
Numerous Numeric Fields to 1 Numeric Field in New Table
with numerous numeric fields to a new table (B) with just one numeric field.
Thus the number of records in the table (B) would be the number or records
in A mutliplied by the number of numeric fields.
Thanks in advance
Please include DDL with your questions so that we don't have to guess at what
your tables might look like.
Here's an example. Suppose you have a denormalized structure like this:
CREATE TABLE monthly_accounts (account_no INTEGER PRIMARY KEY, jan INTEGER
NULL, feb INTEGER NULL, mar INTEGER NULL, ...)
You can convert this to a more usable form as follows:
CREATE TABLE accounts (account_no INTEGER NOT NULL, dt DATETIME NOT NULL
CHECK (DAY(dt)=1), amount INTEGER NOT NULL, PRIMARY KEY (account_no, dt))
INSERT INTO accounts (account_no, dt, amount)
SELECT account_no, '20040101', jan
FROM monthly_accounts
WHERE jan IS NOT NULL
UNION ALL
SELECT account_no, '20040201', feb
FROM monthly_accounts
WHERE feb IS NOT NULL
UNION ALL
SELECT account_no, '20040301', mar
FROM monthly_accounts
WHERE mar IS NOT NULL
...
Notice that you will usually add at least one column to the key when you do
this.
David Portas
SQL Server MVP
|||Thanks David
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:E5E28C97-6FF6-4EBA-8152-33063A6C813C@.microsoft.com...
> Please include DDL with your questions so that we don't have to guess at
what
> your tables might look like.
> Here's an example. Suppose you have a denormalized structure like this:
> CREATE TABLE monthly_accounts (account_no INTEGER PRIMARY KEY, jan INTEGER
> NULL, feb INTEGER NULL, mar INTEGER NULL, ...)
> You can convert this to a more usable form as follows:
> CREATE TABLE accounts (account_no INTEGER NOT NULL, dt DATETIME NOT NULL
> CHECK (DAY(dt)=1), amount INTEGER NOT NULL, PRIMARY KEY (account_no, dt))
> INSERT INTO accounts (account_no, dt, amount)
> SELECT account_no, '20040101', jan
> FROM monthly_accounts
> WHERE jan IS NOT NULL
> UNION ALL
> SELECT account_no, '20040201', feb
> FROM monthly_accounts
> WHERE feb IS NOT NULL
> UNION ALL
> SELECT account_no, '20040301', mar
> FROM monthly_accounts
> WHERE mar IS NOT NULL
> ...
> Notice that you will usually add at least one column to the key when you
do
> this.
> --
> David Portas
> SQL Server MVP
> --
|||Hi
I occasionally concatenate field names from sysColumn rows (by object) in
order to save myself the typing (in sprocs, etc.). Don't see any reason why
you couldn't add the values in your case (if this is what you're trying to
do).
example:
CREATE PROCEDURE dbo.sp_tablecolumns
@.object_id varchar(100)
AS
DECLARE @.FldCat1 VARCHAR(8000)
SET @.FldCat1=''
SELECT @.FldCat1=@.FldCat1+(sysColumns.name + char(44))
FROM sysColumns with (NOLOCK)
WHERE id = object_id(@.object_id)
ORDER BY sysColumns.colorder
PRINT @.FldCat1
GO
usage: dbo.sp_tablecolumns 'MyTableNamethatIwantfieldsfor'
rob
"Joe" wrote:
> Are there any routines out there that will automatically convert a table (A)
> with numerous numeric fields to a new table (B) with just one numeric field.
> Thus the number of records in the table (B) would be the number or records
> in A mutliplied by the number of numeric fields.
> Thanks in advance
>
>
|||sorry, I get what you're saying now.
u can do the same kind of thing I mentioned in my 1st post. u'd have to find
the numeric columns from table A first, loop thru A (by row and then columns)
and do the insert (into B) in the loops.
u could write a generic routine starting with the code I posted.
rob
"RobKaratzas" wrote:
[vbcol=seagreen]
> Hi
> I occasionally concatenate field names from sysColumn rows (by object) in
> order to save myself the typing (in sprocs, etc.). Don't see any reason why
> you couldn't add the values in your case (if this is what you're trying to
> do).
> example:
> CREATE PROCEDURE dbo.sp_tablecolumns
> @.object_id varchar(100)
> AS
> DECLARE @.FldCat1 VARCHAR(8000)
> SET @.FldCat1=''
> SELECT @.FldCat1=@.FldCat1+(sysColumns.name + char(44))
> FROM sysColumns with (NOLOCK)
> WHERE id = object_id(@.object_id)
> ORDER BY sysColumns.colorder
> PRINT @.FldCat1
> GO
> usage: dbo.sp_tablecolumns 'MyTableNamethatIwantfieldsfor'
> rob
> "Joe" wrote:
|||> I occasionally concatenate field names from sysColumn rows (by
object) in
> order to save myself the typing (in sprocs, etc.).
In SQL2000 Query Analyzer can do that automatically for you. Just drag
the Columns node from the Object Browser into the editing window. In
7.0 and earlier you don't have Object Browser so the method you
described may be useful. Not sure what it has to do with Joe's question
though :-)
David Portas
SQL Server MVP
|||What I usually do to copy the column names is
Setting the Result to Text option and then do a
SELECT * FROM table WHERe 1 = 0
Roji. P. Thomas
Net Asset Management
https://www.netassetmanagement.com
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:1103200824.858097.15460@.z14g2000cwz.googlegro ups.com...
> object) in
> In SQL2000 Query Analyzer can do that automatically for you. Just drag
> the Columns node from the Object Browser into the editing window. In
> 7.0 and earlier you don't have Object Browser so the method you
> described may be useful. Not sure what it has to do with Joe's question
> though :-)
> --
> David Portas
> SQL Server MVP
> --
>
|||thanks Roji
I did misread the original post.
But in order to handle this problem with a generic solution, you're going to
require some means to programatically gather what these numerous columns are
for whatever Table A has.
Rob
"Roji. P. Thomas" wrote:
> What I usually do to copy the column names is
> Setting the Result to Text option and then do a
> SELECT * FROM table WHERe 1 = 0
>
> --
> Roji. P. Thomas
> Net Asset Management
> https://www.netassetmanagement.com
>
> "David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
> news:1103200824.858097.15460@.z14g2000cwz.googlegro ups.com...
>
>
sql
Numerous Numeric Fields to 1 Numeric Field in New Table
with numerous numeric fields to a new table (B) with just one numeric field.
Thus the number of records in the table (B) would be the number or records
in A mutliplied by the number of numeric fields.
Thanks in advance
Please include DDL with your questions so that we don't have to guess at what
your tables might look like.
Here's an example. Suppose you have a denormalized structure like this:
CREATE TABLE monthly_accounts (account_no INTEGER PRIMARY KEY, jan INTEGER
NULL, feb INTEGER NULL, mar INTEGER NULL, ...)
You can convert this to a more usable form as follows:
CREATE TABLE accounts (account_no INTEGER NOT NULL, dt DATETIME NOT NULL
CHECK (DAY(dt)=1), amount INTEGER NOT NULL, PRIMARY KEY (account_no, dt))
INSERT INTO accounts (account_no, dt, amount)
SELECT account_no, '20040101', jan
FROM monthly_accounts
WHERE jan IS NOT NULL
UNION ALL
SELECT account_no, '20040201', feb
FROM monthly_accounts
WHERE feb IS NOT NULL
UNION ALL
SELECT account_no, '20040301', mar
FROM monthly_accounts
WHERE mar IS NOT NULL
...
Notice that you will usually add at least one column to the key when you do
this.
David Portas
SQL Server MVP
|||Thanks David
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:E5E28C97-6FF6-4EBA-8152-33063A6C813C@.microsoft.com...
> Please include DDL with your questions so that we don't have to guess at
what
> your tables might look like.
> Here's an example. Suppose you have a denormalized structure like this:
> CREATE TABLE monthly_accounts (account_no INTEGER PRIMARY KEY, jan INTEGER
> NULL, feb INTEGER NULL, mar INTEGER NULL, ...)
> You can convert this to a more usable form as follows:
> CREATE TABLE accounts (account_no INTEGER NOT NULL, dt DATETIME NOT NULL
> CHECK (DAY(dt)=1), amount INTEGER NOT NULL, PRIMARY KEY (account_no, dt))
> INSERT INTO accounts (account_no, dt, amount)
> SELECT account_no, '20040101', jan
> FROM monthly_accounts
> WHERE jan IS NOT NULL
> UNION ALL
> SELECT account_no, '20040201', feb
> FROM monthly_accounts
> WHERE feb IS NOT NULL
> UNION ALL
> SELECT account_no, '20040301', mar
> FROM monthly_accounts
> WHERE mar IS NOT NULL
> ...
> Notice that you will usually add at least one column to the key when you
do
> this.
> --
> David Portas
> SQL Server MVP
> --
|||Hi
I occasionally concatenate field names from sysColumn rows (by object) in
order to save myself the typing (in sprocs, etc.). Don't see any reason why
you couldn't add the values in your case (if this is what you're trying to
do).
example:
CREATE PROCEDURE dbo.sp_tablecolumns
@.object_id varchar(100)
AS
DECLARE @.FldCat1 VARCHAR(8000)
SET @.FldCat1=''
SELECT @.FldCat1=@.FldCat1+(sysColumns.name + char(44))
FROM sysColumns with (NOLOCK)
WHERE id = object_id(@.object_id)
ORDER BY sysColumns.colorder
PRINT @.FldCat1
GO
usage: dbo.sp_tablecolumns 'MyTableNamethatIwantfieldsfor'
rob
"Joe" wrote:
> Are there any routines out there that will automatically convert a table (A)
> with numerous numeric fields to a new table (B) with just one numeric field.
> Thus the number of records in the table (B) would be the number or records
> in A mutliplied by the number of numeric fields.
> Thanks in advance
>
>
|||sorry, I get what you're saying now.
u can do the same kind of thing I mentioned in my 1st post. u'd have to find
the numeric columns from table A first, loop thru A (by row and then columns)
and do the insert (into B) in the loops.
u could write a generic routine starting with the code I posted.
rob
"RobKaratzas" wrote:
[vbcol=seagreen]
> Hi
> I occasionally concatenate field names from sysColumn rows (by object) in
> order to save myself the typing (in sprocs, etc.). Don't see any reason why
> you couldn't add the values in your case (if this is what you're trying to
> do).
> example:
> CREATE PROCEDURE dbo.sp_tablecolumns
> @.object_id varchar(100)
> AS
> DECLARE @.FldCat1 VARCHAR(8000)
> SET @.FldCat1=''
> SELECT @.FldCat1=@.FldCat1+(sysColumns.name + char(44))
> FROM sysColumns with (NOLOCK)
> WHERE id = object_id(@.object_id)
> ORDER BY sysColumns.colorder
> PRINT @.FldCat1
> GO
> usage: dbo.sp_tablecolumns 'MyTableNamethatIwantfieldsfor'
> rob
> "Joe" wrote:
|||> I occasionally concatenate field names from sysColumn rows (by
object) in
> order to save myself the typing (in sprocs, etc.).
In SQL2000 Query Analyzer can do that automatically for you. Just drag
the Columns node from the Object Browser into the editing window. In
7.0 and earlier you don't have Object Browser so the method you
described may be useful. Not sure what it has to do with Joe's question
though :-)
David Portas
SQL Server MVP
|||What I usually do to copy the column names is
Setting the Result to Text option and then do a
SELECT * FROM table WHERe 1 = 0
Roji. P. Thomas
Net Asset Management
https://www.netassetmanagement.com
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:1103200824.858097.15460@.z14g2000cwz.googlegro ups.com...
> object) in
> In SQL2000 Query Analyzer can do that automatically for you. Just drag
> the Columns node from the Object Browser into the editing window. In
> 7.0 and earlier you don't have Object Browser so the method you
> described may be useful. Not sure what it has to do with Joe's question
> though :-)
> --
> David Portas
> SQL Server MVP
> --
>
|||thanks Roji
I did misread the original post.
But in order to handle this problem with a generic solution, you're going to
require some means to programatically gather what these numerous columns are
for whatever Table A has.
Rob
"Roji. P. Thomas" wrote:
> What I usually do to copy the column names is
> Setting the Result to Text option and then do a
> SELECT * FROM table WHERe 1 = 0
>
> --
> Roji. P. Thomas
> Net Asset Management
> https://www.netassetmanagement.com
>
> "David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
> news:1103200824.858097.15460@.z14g2000cwz.googlegro ups.com...
>
>
Numerous Numeric Fields to 1 Numeric Field in New Table
with numerous numeric fields to a new table (B) with just one numeric field.
Thus the number of records in the table (B) would be the number or records
in A mutliplied by the number of numeric fields.
Thanks in advanceHi
I occasionally concatenate field names from sysColumn rows (by object) in
order to save myself the typing (in sprocs, etc.). Don't see any reason why
you couldn't add the values in your case (if this is what you're trying to
do).
example:
CREATE PROCEDURE dbo.sp_tablecolumns
@.object_id varchar(100)
AS
DECLARE @.FldCat1 VARCHAR(8000)
SET @.FldCat1=''
SELECT @.FldCat1=@.FldCat1+(sysColumns.name + char(44))
FROM sysColumns with (NOLOCK)
WHERE id = object_id(@.object_id)
ORDER BY sysColumns.colorder
PRINT @.FldCat1
GO
usage: dbo.sp_tablecolumns 'MyTableNamethatIwantfieldsfor'
rob
"Joe" wrote:
> Are there any routines out there that will automatically convert a table (
A)
> with numerous numeric fields to a new table (B) with just one numeric fiel
d.
> Thus the number of records in the table (B) would be the number or record
s
> in A mutliplied by the number of numeric fields.
> Thanks in advance
>
>|||sorry, I get what you're saying now.
u can do the same kind of thing I mentioned in my 1st post. u'd have to find
the numeric columns from table A first, loop thru A (by row and then columns
)
and do the insert (into B) in the loops.
u could write a generic routine starting with the code I posted.
rob
"RobKaratzas" wrote:
> Hi
> I occasionally concatenate field names from sysColumn rows (by object) in
> order to save myself the typing (in sprocs, etc.). Don't see any reason wh
y
> you couldn't add the values in your case (if this is what you're trying to
> do).
> example:
> CREATE PROCEDURE dbo.sp_tablecolumns
> @.object_id varchar(100)
> AS
> DECLARE @.FldCat1 VARCHAR(8000)
> SET @.FldCat1=''
> SELECT @.FldCat1=@.FldCat1+(sysColumns.name + char(44))
> FROM sysColumns with (NOLOCK)
> WHERE id = object_id(@.object_id)
> ORDER BY sysColumns.colorder
> PRINT @.FldCat1
> GO
> usage: dbo.sp_tablecolumns 'MyTableNamethatIwantfieldsfor'
> rob
> "Joe" wrote:
>|||> I occasionally concatenate field names from sysColumn rows (by
object) in
> order to save myself the typing (in sprocs, etc.).
In SQL2000 Query Analyzer can do that automatically for you. Just drag
the Columns node from the Object Browser into the editing window. In
7.0 and earlier you don't have Object Browser so the method you
described may be useful. Not sure what it has to do with Joe's question
though :-)
David Portas
SQL Server MVP
--|||What I usually do to copy the column names is
Setting the Result to Text option and then do a
SELECT * FROM table WHERe 1 = 0
Roji. P. Thomas
Net Asset Management
https://www.netassetmanagement.com
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:1103200824.858097.15460@.z14g2000cwz.googlegroups.com...
> object) in
> In SQL2000 Query Analyzer can do that automatically for you. Just drag
> the Columns node from the Object Browser into the editing window. In
> 7.0 and earlier you don't have Object Browser so the method you
> described may be useful. Not sure what it has to do with Joe's question
> though :-)
> --
> David Portas
> SQL Server MVP
> --
>|||thanks Roji
I did misread the original post.
But in order to handle this problem with a generic solution, you're going to
require some means to programatically gather what these numerous columns are
for whatever Table A has.
Rob
"Roji. P. Thomas" wrote:
> What I usually do to copy the column names is
> Setting the Result to Text option and then do a
> SELECT * FROM table WHERe 1 = 0
>
> --
> Roji. P. Thomas
> Net Asset Management
> https://www.netassetmanagement.com
>
> "David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
> news:1103200824.858097.15460@.z14g2000cwz.googlegroups.com...
>
>
Numerous Numeric Fields to 1 Numeric Field in New Table
with numerous numeric fields to a new table (B) with just one numeric field.
Thus the number of records in the table (B) would be the number or records
in A mutliplied by the number of numeric fields.
Thanks in advance
Hi
I occasionally concatenate field names from sysColumn rows (by object) in
order to save myself the typing (in sprocs, etc.). Don't see any reason why
you couldn't add the values in your case (if this is what you're trying to
do).
example:
CREATE PROCEDURE dbo.sp_tablecolumns
@.object_id varchar(100)
AS
DECLARE @.FldCat1 VARCHAR(8000)
SET @.FldCat1=''
SELECT @.FldCat1=@.FldCat1+(sysColumns.name + char(44))
FROM sysColumns with (NOLOCK)
WHERE id = object_id(@.object_id)
ORDER BY sysColumns.colorder
PRINT @.FldCat1
GO
usage: dbo.sp_tablecolumns 'MyTableNamethatIwantfieldsfor'
rob
"Joe" wrote:
> Are there any routines out there that will automatically convert a table (A)
> with numerous numeric fields to a new table (B) with just one numeric field.
> Thus the number of records in the table (B) would be the number or records
> in A mutliplied by the number of numeric fields.
> Thanks in advance
>
>
|||sorry, I get what you're saying now.
u can do the same kind of thing I mentioned in my 1st post. u'd have to find
the numeric columns from table A first, loop thru A (by row and then columns)
and do the insert (into B) in the loops.
u could write a generic routine starting with the code I posted.
rob
"RobKaratzas" wrote:
[vbcol=seagreen]
> Hi
> I occasionally concatenate field names from sysColumn rows (by object) in
> order to save myself the typing (in sprocs, etc.). Don't see any reason why
> you couldn't add the values in your case (if this is what you're trying to
> do).
> example:
> CREATE PROCEDURE dbo.sp_tablecolumns
> @.object_id varchar(100)
> AS
> DECLARE @.FldCat1 VARCHAR(8000)
> SET @.FldCat1=''
> SELECT @.FldCat1=@.FldCat1+(sysColumns.name + char(44))
> FROM sysColumns with (NOLOCK)
> WHERE id = object_id(@.object_id)
> ORDER BY sysColumns.colorder
> PRINT @.FldCat1
> GO
> usage: dbo.sp_tablecolumns 'MyTableNamethatIwantfieldsfor'
> rob
> "Joe" wrote:
|||> I occasionally concatenate field names from sysColumn rows (by
object) in
> order to save myself the typing (in sprocs, etc.).
In SQL2000 Query Analyzer can do that automatically for you. Just drag
the Columns node from the Object Browser into the editing window. In
7.0 and earlier you don't have Object Browser so the method you
described may be useful. Not sure what it has to do with Joe's question
though :-)
David Portas
SQL Server MVP
|||What I usually do to copy the column names is
Setting the Result to Text option and then do a
SELECT * FROM table WHERe 1 = 0
Roji. P. Thomas
Net Asset Management
https://www.netassetmanagement.com
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:1103200824.858097.15460@.z14g2000cwz.googlegro ups.com...
> object) in
> In SQL2000 Query Analyzer can do that automatically for you. Just drag
> the Columns node from the Object Browser into the editing window. In
> 7.0 and earlier you don't have Object Browser so the method you
> described may be useful. Not sure what it has to do with Joe's question
> though :-)
> --
> David Portas
> SQL Server MVP
> --
>
|||thanks Roji
I did misread the original post.
But in order to handle this problem with a generic solution, you're going to
require some means to programatically gather what these numerous columns are
for whatever Table A has.
Rob
"Roji. P. Thomas" wrote:
> What I usually do to copy the column names is
> Setting the Result to Text option and then do a
> SELECT * FROM table WHERe 1 = 0
>
> --
> Roji. P. Thomas
> Net Asset Management
> https://www.netassetmanagement.com
>
> "David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
> news:1103200824.858097.15460@.z14g2000cwz.googlegro ups.com...
>
>
numeric vs. money data types performance considerations or gotchas
We are doing some db cleanup and our monetary fields are not defined consistanly. Most are numeric and some are money data type.
Does anyone know of any performance considerations and/or gotchas regarding these two data types? We'd like to convert all monetary amounts to numeric(10,6) fields.
Any feedback would be greatly appreciated.
thanks, dave
This should have a problem if you are using SQL 4.2.1 or 6.5 and I don;t think you are using them so.
Here's an excerpt from Microsoft SQL Server Books Online:
"Monetary Data
Monetary data represents positive or negative amounts of money. In Microsoft? SQL ServerT 2000, monetary data is stored using the money and smallmoney data types. Monetary data can be stored to an accuracy of four decimal places. Use the money data type to store values in the range from -922,337,203,685,477.5808 through +922,337,203,685,477.5807 (requires 8 bytes to store a value). Use the smallmoney data type to store values in the range from -214,748.3648 through 214,748.3647 (requires 4 bytes to store a value). If a greater number of decimal places are required, use the decimal data type instead."
Numeric Representation of Data
In MS Access, for numeric fields, the decimal places shown can be defined as "Auto" meaning that the database will determine the number of decimal places to show based on the content of the field (i.e. 1.0, 0.75, 1.125).
In SQL Server for the same field, it appears that decimal precision is hard coded resulting in a fixed representation (i.e. 1.000, 0.750, 1.125)
Is there a way to make the decimal representation in SQL Server more like Access where trailing zeros are truncated?
See SQL Server 2005 Books Online topic:
float and real (Transact-SQL)
http://msdn2.microsoft.com/en-us/library/ms173773.aspx
|||Perfect.
thanks for your help.
Wednesday, March 28, 2012
Numer comparison
Hi,
I have table with four fields ID, Date1, Date2,Date3,Date4. Dates are in numeric farmat like 20070927. How can i get largest date (from date1 to date4) on each row. Please suggest query.
Thanks
One posible solution is to unpivot those columns and then use "group by".
Code Block
declare @.t table (
[id] int not null identity unique,
date1 int,
date2 int,
date3 int,
date4 int
)
insert into @.t(date1, date2, date3, date4) values(20070305, 20070401, 20070928, 20070704)
insert into @.t(date1, date2, date3, date4) values(20070315, 20070411, 20070228, 20070714)
select
[id],
max(dt) max_dt
from
@.t as t
unpivot
(
dt
for date_col in ([date1], [date2], [date3], [date4])
) as unpvt
group by
[id]
go
AMB|||
Bukhari wrote:
Hi,
I have table with four fields ID, Date1, Date2,Date3,Date4. Dates are in numeric farmat like 20070927. How can i get largest date (from date1 to date4) on each row. Please suggest query.
Thanks
A function like Oracle's GREATEST would come in handy here
What about
Code Block
CREATE TABLE tableA
( id INT IDENTITY PRIMARY KEY
, date1 INT
, date2 INT
, date3 INT
, date4 INT)
INSERT INTO tableA SELECT 20070927, 20070928, 20070926, 20080927
INSERT INTO tableA SELECT 20070927, 20071028, 20070926, 20060927
SELECT id, MAX(iDate) AS maxdate
FROM
(SELECT id,
CASE i
WHEN 1 THEN date1
WHEN 2 THEN date2
WHEN 3 THEN date3
WHEN 4 THEN date4
END AS iDate
FROM tableA
CROSS JOIN
(SELECT 1 AS i
UNION ALL SELECT 2
UNION ALL SELECT 3
UNION ALL SELECT 4) T) T
GROUP BY id
SELECT id,
CASE
WHEN date1 > date2 AND date1 > date3 AND date1 > date4 THEN date1
WHEN date2 > date3 AND date2 > date4 THEN date2
WHEN date3 > date4 THEN date3
ELSE date4 END AS maxdate
FROM tableA
DROP TABLE tableA
id maxdate
-- --
1 20080927
2 20071028
(2 row(s) affected)
id maxdate
-- --
1 20080927
2 20071028
(2 row(s) affected)
|||First off, I just have to note that this is not really a relational design. Each of these dates should be stored in it's own row, and this is an easy SQL problem.
Second, the best relational solution I have found uses a subquery with a UNION ALL operator to "normalize" the date values for an aggregate:
create table dates
(
dateKey int primary key ,
date1 int,
date2 int,
date3 int,
date4 int
)
insert into dates
select 1, 20070101,20070102,20070103,20070104
union
select 2, 20070201,20070202,20070203,20070104
go
select dateKey,
(select min(date)
from (select date1 as date union all select date2 union all
select date3 union all select date4) as dates) as minDate
from dates
It is really quite fast, but if you need more performance, consider using a CLR function to do this. I have found that this technique is about the same speed with you have a few dates, or less than millions of rows to deal with (and it is certainly easier to code and deploy...)
|||Excilent solution. Thanks very much hunchback and frank.
I will go with CASE--WHEN solution.
|||I was really struggling with it. Thanks a lot Louis.|||I just want to mention that what the solution using "case" is doing is unpivoting. Well, all posted solutions are unpivoting some how.
AMB
|||Can i specify criteria in Where clause? Where maxdate less than last 60 days.
Where maxdate < CONVERT(VARCHAR, DATEADD(day, - 60, GETDATE()), 112)
|||but maxdate is not column so it generate error, how can i use CASE WHEN statement in WHERE clause?
thanks
Yes, but you need to use a derived table:
select *
from ( --your original query goes here
select dateKey,
(select min(date)
from (select date1 as date union all select date2 union all
select date3 union all select date4) as dates) as minDate
from dates) as dateQuery
where minDate > 20070101
or CTE if you are using 2005:
with dateQuery as (
select dateKey,
(select min(date)
from (select date1 as date union all select date2 union all
select date3 union all select date4) as dates) as minDate
from dates )
select *
from dateQuery
where minDate > 20070101
Or you can just repeat the subquery:
select dateKey,
(select min(date)
from (select date1 as date union all select date2 union all
select date3 union all select date4) as dates) as minDate
from dates
where (select min(date)
from (select date1 as date union all select date2 union all
select date3 union all select date4) as dates) > 20070101
But that is the least astetically pleasing...
Add a "having" clause to the solution I suggested.
Code Block
declare @.t table (
[id] int not null identity unique,
date1 int,
date2 int,
date3 int,
date4 int
)
insert into @.t(date1, date2, date3, date4) values(20070305, 20070401, 20070928, 20070704)
insert into @.t(date1, date2, date3, date4) values(20070315, 20070411, 20070228, 20070114)
select
[id],
max(dt) max_dt
from
@.t as t
unpivot
(
dt
for date_col in ([date1], [date2], [date3], [date4])
) as unpvt
group by
[id]
having
max(dt) < CONVERT(CHAR(8), DATEADD(day, - 60, GETDATE()), 112)
go
AMB|||Great Stuff, Thanks
|||Hunchback, nice stuff. I would say that both yours and mine have merits, mine is a bit more clean in one way (I am doing a rowwise operation, so I could include most any kind of operation in mine, whereas yours includes an aggregate that would be limiting, but definitely does what was called for, and if you were doing multiple operations only on the date data, might be a lot faster.
|||Hi Louis,
Well, I would prefer to follow what you mentioned (normalizing) in your first post to this thread.
Thanks,
Alejandro Mesa
P.S. I am the guy who asked you to sign my book (I was staying at the "Red Lion") during this year summit. I hope to see you again, to ask you to sign also the one about DMVs & DMFs.
|||>>Well, I would prefer to follow what you mentioned (normalizing) in your first post to this thread.<<
Amen to that, but I have had to do this sort of operation for other reasons. In our etl, we join a bunch of tables together and then get the earliest update date from all of the joined rows so we can include/exclude rows for ETL.
>>also the one about DMVs & DMFs.<<
I definitely remember. I just hope I ever finish that book
Just to throw another approach into the mix.
create function Util.fn_max( @.p1 int, @.p2 int)
returns int
as
begin
return (select case when @.p1>=@.p2 then @.p1 else @.p2 end as int)
end
Select Util.fn_max(Util.fn_max(Util.fn_max(date1, date2), date3), date4)
Change util to the schema that you want, aka dbo. I keep things like this in a Util schema.
Monday, March 26, 2012
Numbering column with a start number of 109
I have a table as follows:
StatId AgencyID Value
1 10
2 47
3 38
4 59
5 60
.. ..
All the fields in the StatId field is blank. However,
I have to fill up the field in statId starting from
109 with increment of 1 for each row. Altogether I have
about 10,000 row in the above agency table.
Any help as to how to proceed programmatically is highly
appreciated. Thanks in advance.
How will you determine what the order should be? That is, should the row
with AgencyID = 10 have a StatId of 109?
"Jack" <Jack@.discussions.microsoft.com> wrote in message
news:F4B0FBC9-1CFF-4E72-A572-1AA9273C5D29@.microsoft.com...
> Hi,
> I have a table as follows:
> StatId AgencyID Value
> 1 10
> 2 47
> 3 38
> 4 59
> 5 60
> .. ..
> All the fields in the StatId field is blank. However,
> I have to fill up the field in statId starting from
> 109 with increment of 1 for each row. Altogether I have
> about 10,000 row in the above agency table.
> Any help as to how to proceed programmatically is highly
> appreciated. Thanks in advance.
|||That's correct. Row with Agencyid = 10 will have a StatID of 109. Thanks.
"Adam Machanic" wrote:
> How will you determine what the order should be? That is, should the row
> with AgencyID = 10 have a StatId of 109?
>
> "Jack" <Jack@.discussions.microsoft.com> wrote in message
> news:F4B0FBC9-1CFF-4E72-A572-1AA9273C5D29@.microsoft.com...
>
>
|||What's the logic then? How will you programatically number these rows?
You'll probably have to write a loop to manually update the rows, one by
one, based on whatever logic you're ordering them by.
Or, you could try creating a new table with StatId INT IDENTITY(109, 1),
then insert the entire batch at once using INSERT SELECT, with an ORDER BY,
but there is no guarantee that the rows will show up in the right order. So
although you could try that, it may not work the way you want.
"Jack" <Jack@.discussions.microsoft.com> wrote in message
news:65435A6C-DB6B-4828-A4F4-754005BB31E7@.microsoft.com...[vbcol=seagreen]
> That's correct. Row with Agencyid = 10 will have a StatID of 109. Thanks.
> "Adam Machanic" wrote:
row[vbcol=seagreen]
Numbering column with a start number of 109
I have a table as follows:
StatId AgencyID Value
1 10
2 47
3 38
4 59
5 60
.. ..
All the fields in the StatId field is blank. However,
I have to fill up the field in statId starting from
109 with increment of 1 for each row. Altogether I have
about 10,000 row in the above agency table.
Any help as to how to proceed programmatically is highly
appreciated. Thanks in advance.How will you determine what the order should be? That is, should the row
with AgencyID = 10 have a StatId of 109?
"Jack" <Jack@.discussions.microsoft.com> wrote in message
news:F4B0FBC9-1CFF-4E72-A572-1AA9273C5D29@.microsoft.com...
> Hi,
> I have a table as follows:
> StatId AgencyID Value
> 1 10
> 2 47
> 3 38
> 4 59
> 5 60
> .. ..
> All the fields in the StatId field is blank. However,
> I have to fill up the field in statId starting from
> 109 with increment of 1 for each row. Altogether I have
> about 10,000 row in the above agency table.
> Any help as to how to proceed programmatically is highly
> appreciated. Thanks in advance.|||What's the logic then? How will you programatically number these rows?
You'll probably have to write a loop to manually update the rows, one by
one, based on whatever logic you're ordering them by.
Or, you could try creating a new table with StatId INT IDENTITY(109, 1),
then insert the entire batch at once using INSERT SELECT, with an ORDER BY,
but there is no guarantee that the rows will show up in the right order. So
although you could try that, it may not work the way you want.
"Jack" <Jack@.discussions.microsoft.com> wrote in message
news:65435A6C-DB6B-4828-A4F4-754005BB31E7@.microsoft.com...
> That's correct. Row with Agencyid = 10 will have a StatID of 109. Thanks.
> "Adam Machanic" wrote:
> > How will you determine what the order should be? That is, should the
row
> > with AgencyID = 10 have a StatId of 109?
> >
> >
> > "Jack" <Jack@.discussions.microsoft.com> wrote in message
> > news:F4B0FBC9-1CFF-4E72-A572-1AA9273C5D29@.microsoft.com...
> > > Hi,
> > > I have a table as follows:
> > >
> > > StatId AgencyID Value
> > > 1 10
> > > 2 47
> > > 3 38
> > > 4 59
> > > 5 60
> > > .. ..
> > > All the fields in the StatId field is blank. However,
> > > I have to fill up the field in statId starting from
> > > 109 with increment of 1 for each row. Altogether I have
> > > about 10,000 row in the above agency table.
> > >
> > > Any help as to how to proceed programmatically is highly
> > > appreciated. Thanks in advance.
> >
> >
> >
Numbering column with a start number of 109
I have a table as follows:
StatId AgencyID Value
1 10
2 47
3 38
4 59
5 60
. ..
All the fields in the StatId field is blank. However,
I have to fill up the field in statId starting from
109 with increment of 1 for each row. Altogether I have
about 10,000 row in the above agency table.
Any help as to how to proceed programmatically is highly
appreciated. Thanks in advance.How will you determine what the order should be? That is, should the row
with AgencyID = 10 have a StatId of 109?
"Jack" <Jack@.discussions.microsoft.com> wrote in message
news:F4B0FBC9-1CFF-4E72-A572-1AA9273C5D29@.microsoft.com...
> Hi,
> I have a table as follows:
> StatId AgencyID Value
> 1 10
> 2 47
> 3 38
> 4 59
> 5 60
> .. ..
> All the fields in the StatId field is blank. However,
> I have to fill up the field in statId starting from
> 109 with increment of 1 for each row. Altogether I have
> about 10,000 row in the above agency table.
> Any help as to how to proceed programmatically is highly
> appreciated. Thanks in advance.|||That's correct. Row with Agencyid = 10 will have a StatID of 109. Thanks.
"Adam Machanic" wrote:
> How will you determine what the order should be? That is, should the row
> with AgencyID = 10 have a StatId of 109?
>
> "Jack" <Jack@.discussions.microsoft.com> wrote in message
> news:F4B0FBC9-1CFF-4E72-A572-1AA9273C5D29@.microsoft.com...
>
>|||What's the logic then? How will you programatically number these rows?
You'll probably have to write a loop to manually update the rows, one by
one, based on whatever logic you're ordering them by.
Or, you could try creating a new table with StatId INT IDENTITY(109, 1),
then insert the entire batch at once using INSERT SELECT, with an ORDER BY,
but there is no guarantee that the rows will show up in the right order. So
although you could try that, it may not work the way you want.
"Jack" <Jack@.discussions.microsoft.com> wrote in message
news:65435A6C-DB6B-4828-A4F4-754005BB31E7@.microsoft.com...[vbcol=seagreen]
> That's correct. Row with Agencyid = 10 will have a StatID of 109. Thanks.
> "Adam Machanic" wrote:
>
row[vbcol=seagreen]
Number of seconds Between 2 Dates
Can anyone tell me a way of calculating the number of seconds that have
elapsed between 2 date time fields e.g. I would to know the total number of
seconds
between GetDate() and GetDate() - 1
Thanks,
David.Use datediff function.
SELECT Datediff(ss,firstdate, seconddate) as elapsedSec
"David Lee" <dleeid@.internode.on.net> wrote in message
news:123p5tnn2r9b52d@.corp.supernews.com...
> Hi,
> Can anyone tell me a way of calculating the number of seconds that have
> elapsed between 2 date time fields e.g. I would to know the total number
of
> seconds
> between GetDate() and GetDate() - 1
> Thanks,
> David.
>|||Make use of DateDiff function.
Select dateDiff(ss, <<startDate>>, <<EndDate>> )
Best Regards
Vadivel
http://vadivel.blogspot.com
"David Lee" wrote:
> Hi,
> Can anyone tell me a way of calculating the number of seconds that have
> elapsed between 2 date time fields e.g. I would to know the total number o
f
> seconds
> between GetDate() and GetDate() - 1
> Thanks,
> David.
>
>
Wednesday, March 21, 2012
Number of fields in a table?
I would like to store all information on them in this table but that amounts to quite a lot of fields (about 50) and some of these will store a lot of HTML text in them.
Is it best to split the table up for performance reasons or will it make little difference?
Thanks,
JBIf thoes are 50 text fields. Then I would prefer to split. I had faced difficulity with it!|||sreedhark thanks,
Actually only 3 fields are text the others are pretty small fields holding phone numbers, addresses etc.
Would you still split?
Is there a way to query the size of field allocation somehow and is there a magic number that is deemed to be too big in performance terms for the web?
Thanks,
JB|||Well, for text field, using of DataLength you can get how much data is stored in it!
3 fields, I am not sure, It's depend on how much data you are storing! If you are not storing not too large chuncks of data, then we can impliment.
Hope it helps!|||I'd still split. I don't know why I'm fond of it. I guess it makes an easier design to split the login info, and the user data. I'm particular to how I design my databases, but it should be ok to leave them all on one table. However, I personally would put the user data on another table, and have a link table for the login/password, and store the last time of login on that table as well as other info on just logins like remote_addr, and session id.
Number of fields in a table
I am working on a project which requires having a form that must be filled by the user. The number of the fields on this form is arround 150. Is it a good idea to have a database table with 150 fields (columns)? If its not what would be a better approach for this case? Handling this many fields on a windows form is another issue but first I would like to know about how to deal with the data storage.
Any help is appreciated.
Thanks
its very hard to say.... you google for Database Normalisation and read about normalisation and how to normalise data.....
Madhu
|||First of all thanks for your response,
How about if I put the form data into an XML file and keep the rest of data in database? Is it a good idea to hold information about one thing in two seperate format. (database and xml file)
I will not use the values in this form other than displaying them as a report.(Like a guy in a department will fill in the form and send it to another guy in another department for confirmation)
Thanks
|||Hi FlatWhite,
There is no technical problem with having 150 fields in a table, but Madhu's point about normaization is valid and important. The question is whether those 150 fields should really be in the same table, meaning that all the fields are related to the key of the table, or whether they should be normalized across several tables. Understanding normalization is a core part of database design (probably the core part of database design). If you're building a database and you haven't read up on normaization yet, go do that now, before you do anything else. If you don't, you'll have problems later.
As to storing your data across two separate formats, this seems like a bad idea. Nothing wrong with XML, but when you start storing data in disparate formats without a clear technical reason for doing so, you just introduce complexity into your application. The issue with your application is the requirement of filling in 150 fields (a daunting form at best), not with how you store the data. Putting the data in XML won't make the form any easier to fill out, it will just make it more complex to access and back up your data because it will reside in two places.
You will serve you users much better by working out how to reduce the number of fields or at least provide default values for as many as possible so that it doesn't take an hour to fill in the form.
Mike
|||Hi Mike,
Thanks for your reply. Honestly its very nice to hear that there is no technical problem with having 150 fields because I wasn't happy with this so couldn't go any further in my database design. Now I can work on.
I have been reading about normalization and I am really having difficulty of making decision about how to split data into smaller groups. Because the form I am designing is consists of say 50 independent questions. Each question (Or point to be answered) gets minimum three input. (some more) (not all questions in the same format)
Example:
Check the color of the product
Qualitative input = selection of good or bad or OK (in the customers hardcopy form this part is consists of 3 checkboxes)
Quantitative input = how big is the surface to be painted
Further Notes = Any text
From this example I made three fields for this question: ProductColorQuantitative, ProductColorQualitative and ProductColorFurtherNotes. (With roughly 50 questions it makes 150 fields)
In terms of normalization first thing that I can think of is putting every question in a seperate table :) which will not help me at all other than making things worse.
Questions are very technical questions so I don't think number of questions can be reduced.
So far I couldn't come up with a better solution. Since I don't need any of these inputs in anywhere in my program I believe it is better to leave it like it is. Do you agree?
Thanks
|||I can think of having one table for the questions -with just a few fields:
Table: Questionnaire
Columns: Date
ResponderID
SurveyVersion
QuestionNumber
QualInput
QuantInput
Notes
Just tossing out ideas here...
|||This question really takes me back...
For some reason questionnair design was one of the most common questions we got when I was supporting Access, so much so that we wrote a KB article to describe a table design that works well for this application and which you can read here. Don't worry that the article applies to Access, relational design is the same regardless of the database where you're designing, all the same concepts apply.
Mike
|||Thanks for the response guys. One last thing that I am trying to figure out is if get three tables such;
Table : Responder
-
ResponderID
Table : Questions
-
QuestionID
Table : Answers
-
AnswerID
QuestionID
ResponderID
Response
I can solve the problem of having somany fields in a single table however since not all the questions get same type of input (some gets int, some gets text, some gets yes or no) I am having trouble in determining the type of the Response field in Answers table.
Am I missing a point in your posts or am I totally in wrong track?
Sorry for bothering you
FlatWhite
|||Since each question could have one of three types of response, create three columns in the table. Use the appropriate column based upon need.Monday, March 19, 2012
number formats (again!)
I'm having a problem with displaying my reports through my application at runtime. One of the formula fields on the report contains the id of the record I'm displaying and if the record's Verified field = True, it also shows a string. The formula is this:
If {?PubNoVer} = "Yes" then
if {View_TM_Get_BookID_BY_Surname.Verified} = True Then
{View_TM_Get_BookID_BY_Surname.BookID} & " Verified"
Else
{View_TM_Get_BookID_BY_Surname.BookID} & " "
Else
" "
In the report preview window, this all looks fine but running it through my application made any four digit id look wrong because it added a thousand separator and decimal places e.g. 1,512.00
In a previous post on another forum, a user very kindly showed me that using ToText on the ID field would get rid of the decimal places, so that's fine, but I still have the thousand separator and can't get rid of it!
Does anyone have any ideas?just format the field
right click on field, select format field, go to number that and select the format u want to display in|||just format the field
right click on field, select format field, go to number that and select the format u want to display in
Yeah, I did that but it only shows the correct format in the preview window, when running the report through the application, it shows the thousand separator and the decimal places even though i'd specified for that not to happen!
OK, I've found half an answer on another site. To get rid of both the decimal places and the thousands separators you use:
ToText({fieldname},0,"")
This works but because I'm also grouping on the id field, the ids still show with a thousands separator on the group tree at the side of the report! Anybody know how to format that?!|||You could create a formula like:
right('0000000000' & totext({fieldname}, 0, ""), 10)
and then group on that formula instead of the fieldname.
Trouble is you get a load of leading zeros in front of the number in the group tree.
You could limit this by finding the maximum length of the field with a whilereadingrecords formula and changing the formula to
right(replicatestring('0', {@.maxlen}) & totext({fieldname}, 0, ""), {@.maxlen})
You could use a space instead of a zero, but the numbers in the group tree won't line up, although they will still be in numeric order.
If anyone knows another way (apart from setting the PC's local settings) I'd like to know...|||You could create a formula like:
right('0000000000' & totext({fieldname}, 0, ""), 10)
and then group on that formula instead of the fieldname.
Trouble is you get a load of leading zeros in front of the number in the group tree.
Thanks JaganEllis. Instead of the formula you suggested, I used ToText({fieldname}, 0, "") and grouped on it and this worked perfectly!|||I can see how that helps with the format of the group tree data, but what about the group ordering? Unless all your number have the same number of digits, the order will be messed up (if important to you).
e.g. 300 will be after 2000 because the string '3' is > the string '2'|||I can see how that helps with the format of the group tree data, but what about the group ordering? Unless all your number have the same number of digits, the order will be messed up (if important to you).
e.g. 300 will be after 2000 because the string '3' is > the string '2'
Ah right... I see what you mean! I've used spaces instead of zeros. Thanks!
Monday, March 12, 2012
NULLS in math
it as zero. Can I use COALESCE or do I need to use CONVERT? Thanks.
Example: Balance = dbo.Table.Amount - dbo.Table.Paid
DavidHi,
use ISNULL function
select ISNULL(field1,0)+ISNULL(field2,0) from Table_name
Thanks
Hari
SQL Server MVP
"David" <dlchase@.lifetimeinc.com> wrote in message
news:OwDq0XNSFHA.1348@.TK2MSFTNGP15.phx.gbl...
>I want to add 2 fields together, but sometimes 1 is NULL and I want to
>treat it as zero. Can I use COALESCE or do I need to use CONVERT? Thanks.
> Example: Balance = dbo.Table.Amount - dbo.Table.Paid
> David
>|||If there is only one value to check for you can also use
ISNULL(Column,[SubstitutionValueIfNull])
.
Coalesce is for comparing different columns, if you want to return the first
NON null value.
Select ISNULL(NULL,0) --> Returns 0
Select COALESCE(NULL,NULL,0) --> returns 0
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--
"David" <dlchase@.lifetimeinc.com> schrieb im Newsbeitrag
news:OwDq0XNSFHA.1348@.TK2MSFTNGP15.phx.gbl...
>I want to add 2 fields together, but sometimes 1 is NULL and I want to
>treat it as zero. Can I use COALESCE or do I need to use CONVERT? Thanks.
> Example: Balance = dbo.Table.Amount - dbo.Table.Paid
> David
>|||>> want to add 2 fields [sic] together, but sometimes 1 is NULL and I
want to treat
it as zero. Can I use COALESCE or do I need to use CONVERT? <<
Columns are not fields; among the MANY important differences is that
columns can be NULL and fields cannot. Use the right mental model and
SQL will be much easier. COALESCE(x, 0.00) is what you are looking
for. CONVERT() is proprietary; you want to use CAST() instead when you
do explicit type casting.
But a better question is how the NULL was allowed in the first place.
People who do not yet know the differences between fields and columns
forget that they need to solve the problems in the DDL with DEFAULT and
CHECK() constraints.|||<snip>...Columns are not fields; among the MANY important differences is tha
t
columns can be NULL and fields cannot... </snip>
As in everything else, semantics plays a great deal in this. You now
have me
so my understanding as to what these terms mean is a mixture of the limited
research I have done, and the practical experence I have in the 'field',
(NPI), with other folks like myself.
So, up to now, I have thought that in posts like the above, you were
'just' arguing against the less than accurate use of words, and the
ambiiguity that results from that. But I'm now wondering if you are talkin
g
about something else.
Exactly what are you talking about when you use the word "field" ? I
didn't think there was such a concept in relatonal database theory, (except
as a misused alias for 'Column', or, sometimes, for 'attribute'). Are you
referring to the OOP concept of field, (an element of data associated wth an
object, or instance of an class) ? Because that concept of 'Field' can
definitely be null...
Or are you referring to some archaic concept of 'field' as understood in
pre-relational databases ?
I also wonder, how do you know which 'other' concept of field, someone is
confuusing this with? Frankly, I believe most of these folks are talking
about columns, as they exist in modern RDBMSs, and are just ignorant of the
academically correct terminology. They are not confusing your concept of
field with the RDBMS concept of a column, they are just using the wrong
word..|||>> have thought that in posts like the above, you were 'just' arguing
against the less than accurate use of words, and the ambiiguity that
results from that. But I'm now wondering if you are talking about
something else. <<
Like most new ideas, the hard part of understanding what the relational
model is comes in un-learning what you know about file systems. As
Artemus Ward (William Graham Sumner, 1840-1910) put it, "It ain't so
much the things we don't know that get us into trouble. It's the things
we know that just ain't so."
If you already have a background in data processing with traditional
file systems, the first things to un-learn are:
(0) Databases are not file sets.
(1) Tables are not files.
(2) Rows are not records.
(3) Columns are not fields.
Modern data processing began with punch cards, or Hollerith cards used
by the Bureau of the Census. Their original size was that of a United
States Dollar bill. This was set by their inventor, Herman Hollerith,
because he could get furniture to store the cards from the United
States Treasury Department, just across the street. Likewise, physical
constraints limited each card to 80 columns of holes in which to record
a symbol.
The influence of the punch card lingered on long after the invention of
magnetic tapes and disk for data storage. This is why early video
display terminals were 80 columns across. Even today, files which
were migrated from cards to magnetic tape files or disk storage still
use 80 column records.
But the influence was not just on the physical side of data processing.
The methods for handling data from the prior media were imitated in
the new media. The programmer kept using sequential, physically
contigous mental models, too.
Data processing first consisted of sorting and merging decks of punch
cards (later, sequential magnetic tape files) in a series of distinct
steps. The result of each step feed into the next step in the process.
Relational databases do not work that way. Each user connects to the
entire database all at once, not to one file at time in a sequence of
steps. The users might not all have the same database access rights
once they are connected, however. Magnetic tapes could not be shared
among users at the same time, but shared data is the point of a
database.
Tables versus Files
A file is closely related to its physical storage media. A table may
or may not be a physical file. DB2 from IBM uses one file per table,
while Sybase puts several entire databases inside one file. A table is
a <i>set<i> of rows of the same kind of thing. A set has no ordering
and it makes no sense to ask for the first or last row.
A deck of punch cards is sequential, and so are magnetic tape files.
Therefore, a <i>physical<i> file of ordered sequential records also
became the <i>mental<i> model for data processing and it is still hard
to shake. Anytime you look at data, it is in some physical ordering.
The various access methods for disk storage system came later, but even
these access methods could not shake the mental model.
Another conceptual difference is that a file is usually data that deals
with a whole business process. A file has to have enough data in
itself to support applications for that business process. Files tend
to be "mixed" data which can be described by the name of the business
process, such as "The Payroll file" or something like that.
Tables can be either entities or relationships within a business
process. This means that the data which was held in one file is often
put into several tables. Tables tend to be "pure" data which can be
described by single words. The payroll would now have separate tables
for timecards, employees, projects and so forth.
Tables as Entities
An entity is physical or conceptual "thing" which has meaning be
itself. A person, a sale or a product would be an example. In a
relational database, an entity is defined by its attributes, which are
shown as values in columns in rows in a table.
To remind users that tables are sets of entities, I like to use plural
or collective nouns that describe the function of the entities within
the system for the names of tables. Thus "Employee" is a bad name
because it is singular; "Employees" is a better name because it is
plural; "Personnel" is best because it is collective and does not
summon up a mental picture of individual persons.
If you have tables with exactly the same structure, then they are sets
of the same kind of elements. But you should have only one set for
each kind of data element! Files, on the other hand, were PHYSICALLY
separate units of storage which coudl be alike -- each tape or disk
file represents a step in the PROCEDURE, such as moving from raw data,
to edited data, and finally to archived data. In SQL, this should be a
status flag in a table.
Tables as Relationships
A relationship is shown in a table by columns which reference one or
more entity tables. Without the entities, the relationship has no
meaning, but the relationship can have attributes of its own. For
example, a show business contract might have an agent, an employer and
a talent. The method of payment is an attribute of the contract
itself, and not of any of the three parties.
Rows versus Records
Rows are not records. A record is defined in the application program
which reads it; a row is defined in the database schema and not by a
program at all. The name of the field in the READ or INPUT statements
of the application; a row is named in the database schema.
All empty files look alike; they are a directory entry in the operating
system with a name and a length of zero bytes of storage. Empty tables
still have columns, constraints, security privileges and other
structures, even tho they have no rows.
This is in keeping with the set theoretical model, in which the empty
set is a perfectly good set. The difference between SQL's set model
and standard mathematical set theory is that set theory has only one
empty set, but in SQL each table has a different structure, so they
cannot be used in places where non-empty versions of themselves could
not be used.
Another characteristic of rows in a table is that they are all alike in
structure and they are all the "same kind of thing" in the model. In a
file system, records can vary in size, datatypes and structure by
having flags in the data stream that tell the program reading the data
how to interpret it. The most common examples are Pascal's variant
record, C's struct syntax and Cobol's OCCURS clause.
The OCCURS keyword in Cobol and the Variant records in Pascal have a
number which tells the program how many time a record structure is to
be repeated in the current record.
Unions in 'C' are not variant records, but variant mappings for the
same physical memory. For example:
union x {int ival; char j[4];} myStuff;
defines myStuff to be either an integer (which are 4 bytes on most
modern C compilers, but this code is non-portable) or an array of 4
bytes, depending on whether you say myStuff.ival or myStuff.j[0];
But even more than that, files often contained records which were
summaries of subsets of the other records -- so called control break
reports. There is no requirement that the records in a file be related
in any way -- they are literally a stream of binary data whose meaning
is assigned by the program reading them.
Columns versus Fields
A field within a record is defined by the application program that
reads it. A column in a row in a table is defined by the database
schema. The datatypes in a column are always scalar.
The order of the application program variables in the READ or INPUT
statements is important because the values are read into the program
variables in that order. In SQL, columns are referenced only by their
names. Yes, there are shorthands like the SELECT * clause and INSERT
INTO <table name> statements which expand into a list of column names
in the physical order in which the column names appear within their
table declaration, but these are shorthands which resolve to named
lists.
The use of NULLs in SQL is also unique to the language. Fields do not
support a missing data marker as part of the field, record or file
itself. Nor do fields have constraints which can be added to them in
the record, like the DEFAULT and CHECK() clauses in SQL.
Relationships among tables within a database
Files are pretty passive creatures and will take whatever an
application program throws at them without much objection. Files are
also independent of each other simply because they are connected to one
application program at a time and therefore have no idea what other
files looks like.
A database actively s
The methods used are triggers, constraints and declarative referential
integrity.
Declarative referential integrity (DRI) says, in effect, that data in
one table has a particular relationship with data in a second (possibly
the same) table. It is also possible to have the database change
itself via referential actions associated with the DRI.
For example, a business rule might be that we do not sell products
which are not in inventory. This rule would be enforce by a REFERENCES
clause on the Orders table which references the Inventory table and a
referential action of ON DELETE CASCADE
Triggers are a more general way of doing much the same thing as DRI. A
trigger is a block of procedural code which is executed before, after
or instead of an INSERT INTO or UPDATE statement. You can do anything
with a trigger that you can do with DRI and more.
However, there are problems with TRIGGERs. While there is a standard
syntax for them in the SQL-92 standard, most vendors have not
implemented it. What they have is very proprietary syntax instead.
Secondly, a trigger cannot pass information to the optimizer like DRI.
In the example in this section, I know that for every product number in
the Orders table, I have that same product number in the Inventory
table. The optimizer can use that information in setting up EXISTS()
predicates and JOINs in the queries. There is no reasonable way to
parse procedural trigger code to determine this relationship.
The CREATE ASSERTION statement in SQL-92 will allow the database to
enforce conditions on the entire database as a whole. An ASSERTION is
not like a CHECK() clause, but the difference is subtle. A CHECK()
clause is executed when there are rows in the table to which it is
attached. If the table is empty then all CHECK() clauses are
effectively TRUE. Thus, if we wanted to be sure that the Inventory
table is never empty, and we wrote:
CREATE TABLE Inventory
( ...
CONSTRAINT inventory_not_empty
CHECK ((SELECT COUNT(*) FROM Inventory) > 0), ... );
it would not work. However, we could write:
CREATE ASSERTION Inventory_not_empty
CHECK ((SELECT COUNT(*) FROM Inventory) > 0);
and we would get the desired results. The assertion is checked at the
schema level and not at the table level.|||Well, thanks for nvesting so much effort in replying. I appreiciate..
So, the short answer to my question, then, is that you assume that people
who use th word field, instead of column, or Record instead of Row, are
talking about Data Processing systems as designed in the 50s an 60s.
I don't even remember those systems, Joe, and I would wager that the
great majority of the people who read your comments here don't remember them
either (or even know they existed). I'd bet that most of the folks who use
RDBMSs today were introduced to database systems using an RDBMS. A majority
of the remainder probably started wit hX-Base systems in the late 1970s or
early 80s.
If I could guess the motivation behind your comments, I'd guess that it
has something to do with the general lack of knowledge and understanding of
relational database theory exhibited by people who use this technology, and
in this I totally agree with you. As I mentioned in my last post I was not
a
CS major and I have learned about this material only through extensive
self-study and research. Unfortunately, it is not an area where one's lack
of knowledge is immediately obvious and/or fatal. It is, unfortunately, all
too easy to think you know what you are doing when you really don't.
So, after learning my lessopn in numerous ways, I sympathize with your
concern about the general lack of understanding of these concepts that seem
s
to exist within our industry. But I can tell you, at least from my
experience, that your logical approach, of using someones terminology as a
hook or segway to present the ways in which Relational Database objects (lik
e
Tables, Columns, Rows, etc.) are different from non-relational file-based
data processing objects (like Files, Fields, and records) often falls on
deaf ears, or is just simply confusing,, becaue most people are simply not
educated about those other file-based systems in the first place. They are
not thnking "old-style" as opposed to a new paradigm, they are simply
ognorant of any school or approach. To the degree that they know anything
about database theory, what they do know are probably bits and pieces of
Relational theory, not pre-relational theory.
So what I am saying is that you probably shouldn't focus so much on the
words ppeople use, (And I don't mean that the words are not important, they
are, and people should be corrected when they misuse them), but the words
don't betray as much about what they do or do not understand or
misunderstand, they just convey ignorance of the proper words.
The place to get a deeper understanding about what some poster does or
does not understand about relational database theory is in the structure of
the databases they post and the questions they ask us to solve, not in the
words they use...
"A rose, by any other name, ..." if you follow me...
And I thought the quote ...
<snip>"It ain't so much the things we don't know that get us into trouble.
It's the things we know that just ain't so."</snip>
was from Will Rogers !!
"--CELKO--" wrote:
> against the less than accurate use of words, and the ambiiguity that
> results from that. But I'm now wondering if you are talking about
> something else. <<
> Like most new ideas, the hard part of understanding what the relational
> model is comes in un-learning what you know about file systems. As
> Artemus Ward (William Graham Sumner, 1840-1910) put it, "It ain't so
> much the things we don't know that get us into trouble. It's the things
> we know that just ain't so."
> If you already have a background in data processing with traditional
> file systems, the first things to un-learn are:
> (0) Databases are not file sets.
> (1) Tables are not files.
> (2) Rows are not records.
> (3) Columns are not fields.
> Modern data processing began with punch cards, or Hollerith cards used
> by the Bureau of the Census. Their original size was that of a United
> States Dollar bill. This was set by their inventor, Herman Hollerith,
> because he could get furniture to store the cards from the United
> States Treasury Department, just across the street. Likewise, physical
> constraints limited each card to 80 columns of holes in which to record
> a symbol.
> The influence of the punch card lingered on long after the invention of
> magnetic tapes and disk for data storage. This is why early video
> display terminals were 80 columns across. Even today, files which
> were migrated from cards to magnetic tape files or disk storage still
> use 80 column records.
> But the influence was not just on the physical side of data processing.
> The methods for handling data from the prior media were imitated in
> the new media. The programmer kept using sequential, physically
> contigous mental models, too.
> Data processing first consisted of sorting and merging decks of punch
> cards (later, sequential magnetic tape files) in a series of distinct
> steps. The result of each step feed into the next step in the process.
>
> Relational databases do not work that way. Each user connects to the
> entire database all at once, not to one file at time in a sequence of
> steps. The users might not all have the same database access rights
> once they are connected, however. Magnetic tapes could not be shared
> among users at the same time, but shared data is the point of a
> database.
> Tables versus Files
> A file is closely related to its physical storage media. A table may
> or may not be a physical file. DB2 from IBM uses one file per table,
> while Sybase puts several entire databases inside one file. A table is
> a <i>set<i> of rows of the same kind of thing. A set has no ordering
> and it makes no sense to ask for the first or last row.
> A deck of punch cards is sequential, and so are magnetic tape files.
> Therefore, a <i>physical<i> file of ordered sequential records also
> became the <i>mental<i> model for data processing and it is still hard
> to shake. Anytime you look at data, it is in some physical ordering.
> The various access methods for disk storage system came later, but even
> these access methods could not shake the mental model.
> Another conceptual difference is that a file is usually data that deals
> with a whole business process. A file has to have enough data in
> itself to support applications for that business process. Files tend
> to be "mixed" data which can be described by the name of the business
> process, such as "The Payroll file" or something like that.
> Tables can be either entities or relationships within a business
> process. This means that the data which was held in one file is often
> put into several tables. Tables tend to be "pure" data which can be
> described by single words. The payroll would now have separate tables
> for timecards, employees, projects and so forth.
> Tables as Entities
> An entity is physical or conceptual "thing" which has meaning be
> itself. A person, a sale or a product would be an example. In a
> relational database, an entity is defined by its attributes, which are
> shown as values in columns in rows in a table.
> To remind users that tables are sets of entities, I like to use plural
> or collective nouns that describe the function of the entities within
> the system for the names of tables. Thus "Employee" is a bad name
> because it is singular; "Employees" is a better name because it is
> plural; "Personnel" is best because it is collective and does not
> summon up a mental picture of individual persons.
> If you have tables with exactly the same structure, then they are sets
> of the same kind of elements. But you should have only one set for
> each kind of data element! Files, on the other hand, were PHYSICALLY
> separate units of storage which coudl be alike -- each tape or disk
> file represents a step in the PROCEDURE, such as moving from raw data,
> to edited data, and finally to archived data. In SQL, this should be a
> status flag in a table.
> Tables as Relationships
> A relationship is shown in a table by columns which reference one or
> more entity tables. Without the entities, the relationship has no
> meaning, but the relationship can have attributes of its own. For
> example, a show business contract might have an agent, an employer and
> a talent. The method of payment is an attribute of the contract
> itself, and not of any of the three parties.
> Rows versus Records
> Rows are not records. A record is defined in the application program
> which reads it; a row is defined in the database schema and not by a
> program at all. The name of the field in the READ or INPUT statements
> of the application; a row is named in the database schema.
> All empty files look alike; they are a directory entry in the operating
> system with a name and a length of zero bytes of storage. Empty tables
> still have columns, constraints, security privileges and other
> structures, even tho they have no rows.
> This is in keeping with the set theoretical model, in which the empty
> set is a perfectly good set. The difference between SQL's set model
> and standard mathematical set theory is that set theory has only one
> empty set, but in SQL each table has a different structure, so they
> cannot be used in places where non-empty versions of themselves could
> not be used.
> Another characteristic of rows in a table is that they are all alike in
> structure and they are all the "same kind of thing" in the model. In a
> file system, records can vary in size, datatypes and structure by
> having flags in the data stream that tell the program reading the data
> how to interpret it. The most common examples are Pascal's variant
> record, C's struct syntax and Cobol's OCCURS clause.
> The OCCURS keyword in Cobol and the Variant records in Pascal have a
> number which tells the program how many time a record structure is to
> be repeated in the current record.
> Unions in 'C' are not variant records, but variant mappings for the
> same physical memory. For example:
> union x {int ival; char j[4];} myStuff;
> defines myStuff to be either an integer (which are 4 bytes on most
> modern C compilers, but this code is non-portable) or an array of 4
> bytes, depending on whether you say myStuff.ival or myStuff.j[0];
> But even more than that, files often contained records which were
> summaries of subsets of the other records -- so called control break
> reports. There is no requirement that the records in a file be related
> in any way -- they are literally a stream of binary data whose meaning
> is assigned by the program reading them.
> Columns versus Fields
> A field within a record is defined by the application program that
> reads it. A column in a row in a table is defined by the database
> schema. The datatypes in a column are always scalar.
> The order of the application program variables in the READ or INPUT
> statements is important because the values are read into the program
> variables in that order. In SQL, columns are referenced only by their
> names. Yes, there are shorthands like the SELECT * clause and INSERT
> INTO <table name> statements which expand into a list of column names
> in the physical order in which the column names appear within their
> table declaration, but these are shorthands which resolve to named
> lists.
> The use of NULLs in SQL is also unique to the language. Fields do not
> support a missing data marker as part of the field, record or file
> itself. Nor do fields have constraints which can be added to them in
> the record, like the DEFAULT and CHECK() clauses in SQL.
> Relationships among tables within a database
> Files are pretty passive creatures and will take whatever an
> application program throws at them without much objection. Files are
> also independent of each other simply because they are connected to one
> application program at a time and therefore have no idea what other
> files looks like.
> A database actively s
> The methods used are triggers, constraints and declarative referential
> integrity.
> Declarative referential integrity (DRI) says, in effect, that data in
> one table has a particular relationship with data in a second (possibly
> the same) table. It is also possible to have the database change
> itself via referential actions associated with the DRI.
> For example, a business rule might be that we do not sell products
> which are not in inventory. This rule would be enforce by a REFERENCES
> clause on the Orders table which references the Inventory table and a
> referential action of ON DELETE CASCADE
> Triggers are a more general way of doing much the same thing as DRI. A
> trigger is a block of procedural code which is executed before, after
> or instead of an INSERT INTO or UPDATE statement. You can do anything
> with a trigger that you can do with DRI and more.
> However, there are problems with TRIGGERs. While there is a standard
> syntax for them in the SQL-92 standard, most vendors have not
> implemented it. What they have is very proprietary syntax instead.
> Secondly, a trigger cannot pass information to the optimizer like DRI.
> In the example in this section, I know that for every product number in
> the Orders table, I have that same product number in the Inventory
> table. The optimizer can use that information in setting up EXISTS()
> predicates and JOINs in the queries. There is no reasonable way to
> parse procedural trigger code to determine this relationship.
> The CREATE ASSERTION statement in SQL-92 will allow the database to
> enforce conditions on the entire database as a whole. An ASSERTION is
> not like a CHECK() clause, but the difference is subtle. A CHECK()
> clause is executed when there are rows in the table to which it is
> attached. If the table is empty then all CHECK() clauses are
> effectively TRUE. Thus, if we wanted to be sure that the Inventory
> table is never empty, and we wrote:
> CREATE TABLE Inventory
> ( ...
> CONSTRAINT inventory_not_empty
> CHECK ((SELECT COUNT(*) FROM Inventory) > 0), ... );
> it would not work. However, we could write:
> CREATE ASSERTION Inventory_not_empty
> CHECK ((SELECT COUNT(*) FROM Inventory) > 0);
> and we would get the desired results. The assertion is checked at the
> schema level and not at the table level.
>
Friday, March 9, 2012
Nullable fields when using SELECT...INTO
Hi,
Could anyone tell me what governs whether a column is set as nullable or not nullable when creating a table using SELECT...INTO. It just seems to pick at random for me! I'm quite sure this is not the case. Is there a way to force a column to be non- nullable? I seem to be wasting a lot of time going through and altering the schema so I can use the columns in keys and indexes.
Dave
Normally the meta data from the original table is retrieved, did oyu check that ?HTH, Jens K. Suessmeyer.
http://www.sqlserver2005.de|||
Jens,
I've checked the source tables and the columns are nullable in there. This is not something I have any control over. Is there no way I can force the columns to be non-nullable in my new table?
Dave
|||YOu will have to put some extra statements after importing the data in the table to change the nullable property of the columns.HTH, Jens K. Suessmeyer.
http://www.sqlserver2005.de|||
Metadata is determined based on the source column and expressions used in the SELECT list. Below are the rules:
1. Any expression that uses a built-in function like SUBSTRING, LEFT, RIGHT etc (except ISNULL) for example is considered as NULLable by the engine. So if you use CAST(somecol as char(8)) then the expression is NULLable
2. Literals, constants, global variables like @.@.DBTS, @.@.ERROR etc are considered non-NULLable since they return some value always
3. If expression is a column then nullability is derived from the source column metadata
So to make an expression or column in the SELECT list not null then use ISNULL around the column or expression.
SELECT isnull(some_null_col, 0) as nc, substring('abc', 1, 1) as null_c1, substring('abc', 1, 1) as non_null_c1
INTO _t
go
exec sp_help '_t'
go
|||
Thanks a lot Umachandar, that's just what I needed to know
Dave
Nullable Bit Field Storage
know that it stores the first 8 bits of a table in the same byte to save
storage, but a nullable bit field is essentially a tri-state and can't
possibly be stored in a single bit.Each row contains a separate null bitmap with a bit representing the null
state of each column.
Hope this helps.
Dan Guzman
SQL Server MVP
"Brad" <me@.privacy.net> wrote in message
news:MPG.1a70ba8015d9aeee98bb01@.news...
quote:|||In article <Oc027982DHA.556@.TK2MSFTNGP11.phx.gbl>, danguzman@.nospam-
> How does SQL store a collection of bit fields when they are nullable? I
> know that it stores the first 8 bits of a table in the same byte to save
> storage, but a nullable bit field is essentially a tri-state and can't
> possibly be stored in a single bit.
earthlink.net said...
quote:
> Each row contains a separate null bitmap with a bit representing the null
> state of each column.
How is that sized? Is it one byte for every eight nullable columns?|||From the Books Online <createdb.chm::/cm_8_des_02_92k3.htm>:
Null Bitmap (Null_Bitmap) = 2 + (( Num_Cols + 7) / 8 )
Hope this helps.
Dan Guzman
SQL Server MVP
"Brad" <me@.privacy.net> wrote in message
news:MPG.1a7133c92572518f98bb05@.news...
quote:
> In article <Oc027982DHA.556@.TK2MSFTNGP11.phx.gbl>, danguzman@.nospam-
> earthlink.net said...
null[QUOTE]
> How is that sized? Is it one byte for every eight nullable columns?
Nullable Bit Field Storage
know that it stores the first 8 bits of a table in the same byte to save
storage, but a nullable bit field is essentially a tri-state and can't
possibly be stored in a single bit.Each row contains a separate null bitmap with a bit representing the null
state of each column.
--
Hope this helps.
Dan Guzman
SQL Server MVP
"Brad" <me@.privacy.net> wrote in message
news:MPG.1a70ba8015d9aeee98bb01@.news...
> How does SQL store a collection of bit fields when they are nullable? I
> know that it stores the first 8 bits of a table in the same byte to save
> storage, but a nullable bit field is essentially a tri-state and can't
> possibly be stored in a single bit.|||In article <Oc027982DHA.556@.TK2MSFTNGP11.phx.gbl>, danguzman@.nospam-
earthlink.net said...
> Each row contains a separate null bitmap with a bit representing the null
> state of each column.
How is that sized? Is it one byte for every eight nullable columns?|||From the Books Online <createdb.chm::/cm_8_des_02_92k3.htm>:
Null Bitmap (Null_Bitmap) = 2 + (( Num_Cols + 7) / 8 )
--
Hope this helps.
Dan Guzman
SQL Server MVP
"Brad" <me@.privacy.net> wrote in message
news:MPG.1a7133c92572518f98bb05@.news...
> In article <Oc027982DHA.556@.TK2MSFTNGP11.phx.gbl>, danguzman@.nospam-
> earthlink.net said...
> > Each row contains a separate null bitmap with a bit representing the
null
> > state of each column.
> How is that sized? Is it one byte for every eight nullable columns?
Wednesday, March 7, 2012
Null values.
my db allows too many null values...i can't do anything to make them not nu
ll as most of the fields can be NULL..
will it affect any performance on my server..and if yes then is there any me
thod where we can avoid the degrading of performance causing by NULL values.
2) doest NULL values really affect server performance.
regards
sanjayNULL is handles like a value in SQL Server. so it doesn't affect performance
any differently compared to if you had an actual value in the column (except
for variable length columns where the NULL "value" only uses space in the
null map in the row layout compared to a real varchar value which is stored
in the row).
Tibor Karaszi, SQL Server MVP
Archive at:
http://groups.google.com/groups?oi=...ublic.sqlserver
"sanjay" <anonymous@.discussions.microsoft.com> wrote in message
news:5556A9CC-C2C3-4900-AB37-C81EB2723A7B@.microsoft.com...
> Hi,
> my db allows too many null values...i can't do anything to make them not
null as most of the fields can be NULL..
> will it affect any performance on my server..and if yes then is there any
method where we can avoid the degrading of performance causing by NULL
values.
> 2) doest NULL values really affect server performance.
> regards
> sanjay
>
Null values.
my db allows too many null values...i can't do anything to make them not null as most of the fields can be NULL.
will it affect any performance on my server..and if yes then is there any method where we can avoid the degrading of performance causing by NULL values
2) doest NULL values really affect server performance
regard
sanjaNULL is handles like a value in SQL Server. so it doesn't affect performance
any differently compared to if you had an actual value in the column (except
for variable length columns where the NULL "value" only uses space in the
null map in the row layout compared to a real varchar value which is stored
in the row).
--
Tibor Karaszi, SQL Server MVP
Archive at:
http://groups.google.com/groups?oi=djq&as_ugroup=microsoft.public.sqlserver
"sanjay" <anonymous@.discussions.microsoft.com> wrote in message
news:5556A9CC-C2C3-4900-AB37-C81EB2723A7B@.microsoft.com...
> Hi,
> my db allows too many null values...i can't do anything to make them not
null as most of the fields can be NULL..
> will it affect any performance on my server..and if yes then is there any
method where we can avoid the degrading of performance causing by NULL
values.
> 2) doest NULL values really affect server performance.
> regards
> sanjay
>