Showing posts with label column. Show all posts
Showing posts with label column. Show all posts

Wednesday, March 28, 2012

How do i make a column using 3 other columns together within the same table

Hello all,

The example to this question is better:

ID PName Ppurchased PSold PSellPrice AvgSellprice
1 Water 50 10 100 20
2 Water 40 20 200 100
3 Water 70 35 50 25

What i want to happen within the table or maybe on a different table is to add the AvgSellprice of all 3 together to where it will look like this in a table:

ID PName Ppurchased PSold PSellPrice AvgSellprice TotalSellPrice
1 Water 50 10 100 20 145
2 Water 40 20 200 100 145
3 Water 70 35 50 25 145

Or maybe a new table which i want to look like this:

ID PName TotalSellPrice
1 Water 145

I know i can get the TotalSellPrice from the query:
SELECT SUM(AvgSellprice) AS TotalSellPrice
FROM tablename
WHERE PName='Water'

Also i am using MSSQL 2005 if this may differ. Thanks for any help.Also within this table there are other entries that do not pertain to the water. They have different names which may complicate things a little, not to sure as i don't know how to write the code for this table.

How do I make a column not nullable

This is what I would like to do...

1. Alter Table Status
Add ConsiderOpenFlag int null

2. UPDATE values...

3. Alter Table Status
Alter ConsiderOpenFlag int not null

Steps 1 and 2 are easy. What I cannot figure out is step three.

I don't want to have a default on that column, though I wouldn't mind adding it and then dropping it later if it would help.

Jonathan

The correct syntax is:

ALTER TABLE Status ALTER COLUMN ConsiderOpenFlag int not null

Best is probably to add the column as not null with default and then drop the default later. If there are large number of rows in the table then you may want to go with the UPDATE method and perform the UPDATE in batches to reduce the logging / locking resources.

sql

Monday, March 26, 2012

How do I know if an index column is in descending order from SQL Server?

Hey all that I want is to be able to run from another DB.
This "sp_MShelpindex" like the "indexkey_property" only work running from
the DB where the index sits.
I need to join this information from multiple DBs in a single query, and I
was wondering if (and how) this is possible.
Thanks
>
> "GregO" <grego@.community.nospam> wrote in message
> news:uX7vlRJrFHA.904@.tk2msftngp13.phx.gbl...
>> Hi Peter
>>
>> EXECUTE sp_MShelpindex N'authors', N'aunmind'
>>
>> try this in PUBS
>>
>> http://www.sql-server-performance.com/ac_sql_server_7_undocumented_sp.asp
>>
>>
>> --
>> kind regards
>> Greg O
>> Need to document your databases. Use the firs and still the best AGS SQL
>> Scribe
>> http://www.ag-software.com
>>
>>
>> "Peter Reid" <noreply@.microsoft.com> wrote in message
>> news:eubQTNIrFHA.904@.tk2msftngp13.phx.gbl...
>> How do I know if an index column is in descending order from SQL Server?
>>
>> I don't want to use "indexkey_property" as it doesn't work from another
>> DB.
>> I also know that I can do something like this:
>>
>> USE <db1>
>> select into a temp table
>>
>> USE <db2>
>> select into another temp table
>>
>>
>> But what I'm actually interested in knowing is where this information is
>> stored in SQL Server (as it doesn't seam to on the sysindexkeys table),
>> and furthermore how to query it.
>>
>> Thanks
>>
>>
>>
>>
>
>Hi Peter
Did you try:
EXECUTE pubs..sp_MShelpindex N'authors', N'aunmind'
John
"Peter Reid" wrote:
> Hey all that I want is to be able to run from another DB.
> This "sp_MShelpindex" like the "indexkey_property" only work running from
> the DB where the index sits.
> I need to join this information from multiple DBs in a single query, and I
> was wondering if (and how) this is possible.
> Thanks
> >
> > "GregO" <grego@.community.nospam> wrote in message
> > news:uX7vlRJrFHA.904@.tk2msftngp13.phx.gbl...
> >> Hi Peter
> >>
> >> EXECUTE sp_MShelpindex N'authors', N'aunmind'
> >>
> >> try this in PUBS
> >>
> >> http://www.sql-server-performance.com/ac_sql_server_7_undocumented_sp.asp
> >>
> >>
> >> --
> >> kind regards
> >> Greg O
> >> Need to document your databases. Use the firs and still the best AGS SQL
> >> Scribe
> >> http://www.ag-software.com
> >>
> >>
> >> "Peter Reid" <noreply@.microsoft.com> wrote in message
> >> news:eubQTNIrFHA.904@.tk2msftngp13.phx.gbl...
> >> How do I know if an index column is in descending order from SQL Server?
> >>
> >> I don't want to use "indexkey_property" as it doesn't work from another
> >> DB.
> >> I also know that I can do something like this:
> >>
> >> USE <db1>
> >> select into a temp table
> >>
> >> USE <db2>
> >> select into another temp table
> >>
> >>
> >> But what I'm actually interested in knowing is where this information is
> >> stored in SQL Server (as it doesn't seam to on the sysindexkeys table),
> >> and furthermore how to query it.
> >>
> >> Thanks
> >>
> >>
> >>
> >>
> >
> >
>
>sql

How do I know if an index column is in descending order from SQL Server?

How do I know if an index column is in descending order from SQL Server?
I don't want to use "indexkey_property" as it doesn't work from another DB.
I also know that I can do something like this:
USE <db1>
select into a temp table
USE <db2>
select into another temp table
But what I'm actually interested in knowing is where this information is
stored in SQL Server (as it doesn't seam to on the sysindexkeys table), and
furthermore how to query it.
ThanksHi Peter
EXECUTE sp_MShelpindex N'authors', N'aunmind'
try this in PUBS
http://www.sql-server-performance.c...cumented_sp.asp
kind regards
Greg O
Need to document your databases. Use the firs and still the best AGS SQL
Scribe
http://www.ag-software.com
"Peter Reid" <noreply@.microsoft.com> wrote in message
news:eubQTNIrFHA.904@.tk2msftngp13.phx.gbl...
> How do I know if an index column is in descending order from SQL Server?
> I don't want to use "indexkey_property" as it doesn't work from another
> DB.
> I also know that I can do something like this:
> USE <db1>
> select into a temp table
> USE <db2>
> select into another temp table
>
> But what I'm actually interested in knowing is where this information is
> stored in SQL Server (as it doesn't seam to on the sysindexkeys table),
> and furthermore how to query it.
> Thanks
>|||Look up the INDEXKEY_PROPERTY function in BOL.
SELECT indexkey_property(OBJECT_ID('authors'),2
,2,'IsDescending')
Roji. P. Thomas
Net Asset Management
http://toponewithties.blogspot.com
"Peter Reid" <noreply@.microsoft.com> wrote in message
news:eubQTNIrFHA.904@.tk2msftngp13.phx.gbl...
> How do I know if an index column is in descending order from SQL Server?
> I don't want to use "indexkey_property" as it doesn't work from another
> DB.
> I also know that I can do something like this:
> USE <db1>
> select into a temp table
> USE <db2>
> select into another temp table
>
> But what I'm actually interested in knowing is where this information is
> stored in SQL Server (as it doesn't seam to on the sysindexkeys table),
> and furthermore how to query it.
> Thanks
>|||Hey all that I want is to be able to run from another DB.
This "sp_MShelpindex" like the "indexkey_property" only work running from
the DB where the index sits.
I need to join this information from multiple DBs in a single query, and I
was wondering if (and how) this is possible.
Thanks
"GregO" <grego@.community.nospam> wrote in message
news:uX7vlRJrFHA.904@.tk2msftngp13.phx.gbl...
> Hi Peter
> EXECUTE sp_MShelpindex N'authors', N'aunmind'
> try this in PUBS
> http://www.sql-server-performance.c...cumented_sp.asp
>
> --
> kind regards
> Greg O
> Need to document your databases. Use the firs and still the best AGS SQL
> Scribe
> http://www.ag-software.com
>
> "Peter Reid" <noreply@.microsoft.com> wrote in message
> news:eubQTNIrFHA.904@.tk2msftngp13.phx.gbl...
>|||Hey all that I want is to be able to run from another DB.
This "sp_MShelpindex" like the "indexkey_property" only work running from
the DB where the index sits.
I need to join this information from multiple DBs in a single query, and I
was wondering if (and how) this is possible.
Thanks

> "GregO" <grego@.community.nospam> wrote in message
> news:uX7vlRJrFHA.904@.tk2msftngp13.phx.gbl...
>

How do I know if an index column is in descending order from SQL Server?

How do I know if an index column is in descending order from SQL Server?
I don't want to use "indexkey_property" as it doesn't work from another DB.
I also know that I can do something like this:
USE <db1>
select into a temp table
USE <db2>
select into another temp table
But what I'm actually interested in knowing is where this information is
stored in SQL Server (as it doesn't seam to on the sysindexkeys table), and
furthermore how to query it.
Thanks
Hi Peter
EXECUTE sp_MShelpindex N'authors', N'aunmind'
try this in PUBS
http://www.sql-server-performance.co...umented_sp.asp
kind regards
Greg O
Need to document your databases. Use the firs and still the best AGS SQL
Scribe
http://www.ag-software.com
"Peter Reid" <noreply@.microsoft.com> wrote in message
news:eubQTNIrFHA.904@.tk2msftngp13.phx.gbl...
> How do I know if an index column is in descending order from SQL Server?
> I don't want to use "indexkey_property" as it doesn't work from another
> DB.
> I also know that I can do something like this:
> USE <db1>
> select into a temp table
> USE <db2>
> select into another temp table
>
> But what I'm actually interested in knowing is where this information is
> stored in SQL Server (as it doesn't seam to on the sysindexkeys table),
> and furthermore how to query it.
> Thanks
>
|||Look up the INDEXKEY_PROPERTY function in BOL.
SELECT indexkey_property(OBJECT_ID('authors'),2,2,'IsDesc ending')
Roji. P. Thomas
Net Asset Management
http://toponewithties.blogspot.com
"Peter Reid" <noreply@.microsoft.com> wrote in message
news:eubQTNIrFHA.904@.tk2msftngp13.phx.gbl...
> How do I know if an index column is in descending order from SQL Server?
> I don't want to use "indexkey_property" as it doesn't work from another
> DB.
> I also know that I can do something like this:
> USE <db1>
> select into a temp table
> USE <db2>
> select into another temp table
>
> But what I'm actually interested in knowing is where this information is
> stored in SQL Server (as it doesn't seam to on the sysindexkeys table),
> and furthermore how to query it.
> Thanks
>
|||Hey all that I want is to be able to run from another DB.
This "sp_MShelpindex" like the "indexkey_property" only work running from
the DB where the index sits.
I need to join this information from multiple DBs in a single query, and I
was wondering if (and how) this is possible.
Thanks
"GregO" <grego@.community.nospam> wrote in message
news:uX7vlRJrFHA.904@.tk2msftngp13.phx.gbl...
> Hi Peter
> EXECUTE sp_MShelpindex N'authors', N'aunmind'
> try this in PUBS
> http://www.sql-server-performance.co...umented_sp.asp
>
> --
> kind regards
> Greg O
> Need to document your databases. Use the firs and still the best AGS SQL
> Scribe
> http://www.ag-software.com
>
> "Peter Reid" <noreply@.microsoft.com> wrote in message
> news:eubQTNIrFHA.904@.tk2msftngp13.phx.gbl...
>
|||Hey all that I want is to be able to run from another DB.
This "sp_MShelpindex" like the "indexkey_property" only work running from
the DB where the index sits.
I need to join this information from multiple DBs in a single query, and I
was wondering if (and how) this is possible.
Thanks

> "GregO" <grego@.community.nospam> wrote in message
> news:uX7vlRJrFHA.904@.tk2msftngp13.phx.gbl...
>

How do I know if an index column is in descending order from SQL Server?

How do I know if an index column is in descending order from SQL Server?
I don't want to use "indexkey_property" as it doesn't work from another DB.
I also know that I can do something like this:
USE <db1>
select into a temp table
USE <db2>
select into another temp table
But what I'm actually interested in knowing is where this information is
stored in SQL Server (as it doesn't seam to on the sysindexkeys table), and
furthermore how to query it.
ThanksHi Peter
EXECUTE sp_MShelpindex N'authors', N'aunmind'
try this in PUBS
http://www.sql-server-performance.com/ac_sql_server_7_undocumented_sp.asp
kind regards
Greg O
Need to document your databases. Use the firs and still the best AGS SQL
Scribe
http://www.ag-software.com
"Peter Reid" <noreply@.microsoft.com> wrote in message
news:eubQTNIrFHA.904@.tk2msftngp13.phx.gbl...
> How do I know if an index column is in descending order from SQL Server?
> I don't want to use "indexkey_property" as it doesn't work from another
> DB.
> I also know that I can do something like this:
> USE <db1>
> select into a temp table
> USE <db2>
> select into another temp table
>
> But what I'm actually interested in knowing is where this information is
> stored in SQL Server (as it doesn't seam to on the sysindexkeys table),
> and furthermore how to query it.
> Thanks
>|||Look up the INDEXKEY_PROPERTY function in BOL.
SELECT indexkey_property(OBJECT_ID('authors'),2,2,'IsDescending')
Roji. P. Thomas
Net Asset Management
http://toponewithties.blogspot.com
"Peter Reid" <noreply@.microsoft.com> wrote in message
news:eubQTNIrFHA.904@.tk2msftngp13.phx.gbl...
> How do I know if an index column is in descending order from SQL Server?
> I don't want to use "indexkey_property" as it doesn't work from another
> DB.
> I also know that I can do something like this:
> USE <db1>
> select into a temp table
> USE <db2>
> select into another temp table
>
> But what I'm actually interested in knowing is where this information is
> stored in SQL Server (as it doesn't seam to on the sysindexkeys table),
> and furthermore how to query it.
> Thanks
>|||Hey all that I want is to be able to run from another DB.
This "sp_MShelpindex" like the "indexkey_property" only work running from
the DB where the index sits.
I need to join this information from multiple DBs in a single query, and I
was wondering if (and how) this is possible.
Thanks
"GregO" <grego@.community.nospam> wrote in message
news:uX7vlRJrFHA.904@.tk2msftngp13.phx.gbl...
> Hi Peter
> EXECUTE sp_MShelpindex N'authors', N'aunmind'
> try this in PUBS
> http://www.sql-server-performance.com/ac_sql_server_7_undocumented_sp.asp
>
> --
> kind regards
> Greg O
> Need to document your databases. Use the firs and still the best AGS SQL
> Scribe
> http://www.ag-software.com
>
> "Peter Reid" <noreply@.microsoft.com> wrote in message
> news:eubQTNIrFHA.904@.tk2msftngp13.phx.gbl...
>> How do I know if an index column is in descending order from SQL Server?
>> I don't want to use "indexkey_property" as it doesn't work from another
>> DB.
>> I also know that I can do something like this:
>> USE <db1>
>> select into a temp table
>> USE <db2>
>> select into another temp table
>>
>> But what I'm actually interested in knowing is where this information is
>> stored in SQL Server (as it doesn't seam to on the sysindexkeys table),
>> and furthermore how to query it.
>> Thanks
>>
>

How do I know if a column is updated?

Hi,
In SQL Server 2000, how do I know that a paricular column in a Table row is
updated?
e.g., in Customer(ID, Name, SSN, DoB, Address),
the (0001, John, 123456789,1980/01/02,'1234 Main Street'),
where the '1234 Main Street' is updated.
Thanks for help.
Jason
You could respond to the change in an UPDATE trigger. In the trigger
you can use the IF UPDATE()
<http://msdn.microsoft.com/library/de...es_08_7377.asp>
clause to determine if any particular column has been changed. For example,
CREATE TRIGGER MyUpdateTrigger ON dbo.MyTable
FOR UPDATE AS
IF UPDATE(MyCol)
BEGIN
...
END
GO
where MyCol is a column in dbo.MyTable that you want to respond to
changes on.
*mike hodgson*
http://sqlnerd.blogspot.com
Jason Huang wrote:

>Hi,
>In SQL Server 2000, how do I know that a paricular column in a Table row is
>updated?
>e.g., in Customer(ID, Name, SSN, DoB, Address),
>the (0001, John, 123456789,1980/01/02,'1234 Main Street'),
>where the '1234 Main Street' is updated.
>Thanks for help.
>
>Jason
>
>

How do I know if a column is updated?

Hi,
In SQL Server 2000, how do I know that a paricular column in a Table row is
updated?
e.g., in Customer(ID, Name, SSN, DoB, Address),
the (0001, John, 123456789,1980/01/02,'1234 Main Street'),
where the '1234 Main Street' is updated.
Thanks for help.
JasonThis is a multi-part message in MIME format.
--020706030805090103030202
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 7bit
You could respond to the change in an UPDATE trigger. In the trigger
you can use the IF UPDATE()
<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/createdb/cm_8_des_08_7377.asp>
clause to determine if any particular column has been changed. For example,
CREATE TRIGGER MyUpdateTrigger ON dbo.MyTable
FOR UPDATE AS
IF UPDATE(MyCol)
BEGIN
...
END
GO
where MyCol is a column in dbo.MyTable that you want to respond to
changes on.
--
*mike hodgson*
http://sqlnerd.blogspot.com
Jason Huang wrote:
>Hi,
>In SQL Server 2000, how do I know that a paricular column in a Table row is
>updated?
>e.g., in Customer(ID, Name, SSN, DoB, Address),
>the (0001, John, 123456789,1980/01/02,'1234 Main Street'),
>where the '1234 Main Street' is updated.
>Thanks for help.
>
>Jason
>
>
--020706030805090103030202
Content-Type: text/html; charset=ISO-8859-1
Content-Transfer-Encoding: 7bit
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html;charset=ISO-8859-1" http-equiv="Content-Type">
<title></title>
</head>
<body bgcolor="#ffffff" text="#000000">
<tt>You could respond to the change in an UPDATE trigger. In the
trigger you can use the <a
href="http://links.10026.com/?link=IF">http://msdn.microsoft.com/library/default.asp?url=/library/en-us/createdb/cm_8_des_08_7377.asp">IF
UPDATE()</a> clause to determine if any particular column has been
changed. For example,<br>
</tt>
<blockquote><tt>CREATE TRIGGER MyUpdateTrigger ON dbo.MyTable</tt><br>
<tt>FOR UPDATE AS</tt><br>
<tt> IF UPDATE(MyCol)</tt><br>
<tt> BEGIN</tt><br>
<tt> ...</tt><br>
<tt> END</tt><br>
<tt>GO</tt><br>
</blockquote>
<tt>where MyCol is a column in dbo.MyTable that you want to respond to
changes on.<br>
</tt>
<div class="moz-signature">
<title></title>
<meta http-equiv="Content-Type" content="text/html; ">
<p><span lang="en-au"><font face="Tahoma" size="2">--<br>
</font></span> <b><span lang="en-au"><font face="Tahoma" size="2">mike
hodgson</font></span></b><span lang="en-au"><br>
<font face="Tahoma" size="2"><a href="http://links.10026.com/?link=http://sqlnerd.blogspot.com</a></font></span>">http://sqlnerd.blogspot.com">http://sqlnerd.blogspot.com</a></font></span>
</p>
</div>
<br>
<br>
Jason Huang wrote:
<blockquote cite="midu8m7SusVGHA.5592@.TK2MSFTNGP09.phx.gbl" type="cite">
<pre wrap="">Hi,
In SQL Server 2000, how do I know that a paricular column in a Table row is
updated?
e.g., in Customer(ID, Name, SSN, DoB, Address),
the (0001, John, 123456789,1980/01/02,'1234 Main Street'),
where the '1234 Main Street' is updated.
Thanks for help.
Jason
</pre>
</blockquote>
</body>
</html>
--020706030805090103030202--

How do I know if a column is updated?

Hi,
In SQL Server 2000, how do I know that a paricular column in a Table row is
updated?
e.g., in Customer(ID, Name, SSN, DoB, Address),
the (0001, John, 123456789,1980/01/02,'1234 Main Street'),
where the '1234 Main Street' is updated.
Thanks for help.
JasonYou could respond to the change in an UPDATE trigger. In the trigger
you can use the IF UPDATE()
<http://msdn.microsoft.com/library/d...
s_08_7377.asp>
clause to determine if any particular column has been changed. For example,
CREATE TRIGGER MyUpdateTrigger ON dbo.MyTable
FOR UPDATE AS
IF UPDATE(MyCol)
BEGIN
..
END
GO
where MyCol is a column in dbo.MyTable that you want to respond to
changes on.
*mike hodgson*
http://sqlnerd.blogspot.com
Jason Huang wrote:

>Hi,
>In SQL Server 2000, how do I know that a paricular column in a Table row is
>updated?
>e.g., in Customer(ID, Name, SSN, DoB, Address),
>the (0001, John, 123456789,1980/01/02,'1234 Main Street'),
>where the '1234 Main Street' is updated.
>Thanks for help.
>
>Jason
>
>

Friday, March 23, 2012

How do I insert a string value with quotes into a nvarchar column

I am reading data from another data source and storing it in the sqlce database. Some of the string values I'm trying to insert into the database have single quotes in the string (i.e. Johnny's Company). When I try to insert the values with the single quotes, it throws an exception. The code I use to insert the records is as follows:

cmd.CommandText = "INSERT sy_company " +

" (company_id, company, co_name, companyid) " +

"VALUES(" +

"'" + dtSYCompany.Rows[x]["company_id"] + "'," +

"N'" + dtSYCompany.Rows[x]["company"] + "'," +

"N'" + dtSYCompany.Rows[x]["co_name"] + "'," +

"'" + dtSYCompany.Rows[x]["companyid"] + "')";

cmd.ExecuteNonQuery();

When the company name (co_name) has a single quote in it, I get the error. How do I write the insert statement so it will work even though the value being inserted into co_name has a single quote in it?

Thanks so much!

Use parameters. It’s also great for performance and security.

By the way, it appears you’re using DataTable. In that case you could use DataAdapter.Update() instead of running commands manually. CommandBuilder can generate parametrized command for you.

|||That did it!!! Thanks so much.

How do I impose the IDENTITY property on an existing column?

How do I impose the IDENTITY property on an existing
column with data in it already? Scenario:
Column "joe" is not an IDENTITY column
Data imported into table and "joe" now has data.
***I want to now assign "joe" the IDENTITY property
without dropping and re-adding the column.
How do I do this?
Thanks,
MikeActually, this method will work as long as "joe" is an integer, as the
identity must be anyway to increment.
This table (YourTable) consisted of joe and jim both integers and initially
loaded, say with these values.
1,2
5,3
3,4
6,3
7,2
We run this script:
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
CREATE TABLE dbo.Tmp_YourTable
(
joe int NOT NULL IDENTITY (1, 1),
jim int NOT NULL
) ON [PRIMARY]
GO
SET IDENTITY_INSERT dbo.Tmp_YourTable ON
GO
IF EXISTS(SELECT * FROM dbo.YourTable)
EXEC('INSERT INTO dbo.Tmp_YourTable (joe, jim)
SELECT joe, jim FROM dbo.YourTable TABLOCKX')
GO
SET IDENTITY_INSERT dbo.Tmp_YourTable OFF
GO
DROP TABLE dbo.YourTable
GO
EXECUTE sp_rename N'dbo.Tmp_YourTable', N'YourTable', 'OBJECT'
GO
COMMIT
Now YourTable has joe as the identity column and the next entry into
YourTable will enter 8 in joe
"Michael Berry" <anontaddler@.hotmail.com> wrote in message
news:2c3201c38e20$b3ed8010$3501280a@.phx.gbl...
> How do I impose the IDENTITY property on an existing
> column with data in it already? Scenario:
> Column "joe" is not an IDENTITY column
> Data imported into table and "joe" now has data.
> ***I want to now assign "joe" the IDENTITY property
> without dropping and re-adding the column.
> How do I do this?
> Thanks,
> Mike|||I cannot have any temporary tables created - I must work
within the confines of one table and the specific column I
have been given - I would like to "toggle" the identity
property as you can in the Enterprise Manager GUI
interface...
Michael
>--Original Message--
>Actually, this method will work as long as "joe" is an
integer, as the
>identity must be anyway to increment.
>This table (YourTable) consisted of joe and jim both
integers and initially
>loaded, say with these values.
>1,2
>5,3
>3,4
>6,3
>7,2
>We run this script:
>BEGIN TRANSACTION
>SET QUOTED_IDENTIFIER ON
>SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
>SET ARITHABORT ON
>SET NUMERIC_ROUNDABORT OFF
>SET CONCAT_NULL_YIELDS_NULL ON
>SET ANSI_NULLS ON
>SET ANSI_PADDING ON
>SET ANSI_WARNINGS ON
>COMMIT
>BEGIN TRANSACTION
>CREATE TABLE dbo.Tmp_YourTable
> (
> joe int NOT NULL IDENTITY (1, 1),
> jim int NOT NULL
> ) ON [PRIMARY]
>GO
>SET IDENTITY_INSERT dbo.Tmp_YourTable ON
>GO
>IF EXISTS(SELECT * FROM dbo.YourTable)
> EXEC('INSERT INTO dbo.Tmp_YourTable (joe, jim)
> SELECT joe, jim FROM dbo.YourTable TABLOCKX')
>GO
>SET IDENTITY_INSERT dbo.Tmp_YourTable OFF
>GO
>DROP TABLE dbo.YourTable
>GO
>EXECUTE sp_rename N'dbo.Tmp_YourTable',
N'YourTable', 'OBJECT'
>GO
>COMMIT
>Now YourTable has joe as the identity column and the next
entry into
>YourTable will enter 8 in joe
>
>"Michael Berry" <anontaddler@.hotmail.com> wrote in message
>news:2c3201c38e20$b3ed8010$3501280a@.phx.gbl...
>> How do I impose the IDENTITY property on an existing
>> column with data in it already? Scenario:
>> Column "joe" is not an IDENTITY column
>> Data imported into table and "joe" now has data.
>> ***I want to now assign "joe" the IDENTITY property
>> without dropping and re-adding the column.
>> How do I do this?
>> Thanks,
>> Mike
>
>.
>

How do I identify whether a column is set up to automatically increment

How do I programmatically identify whether a column is set up to automatically increment? I am looking for a field in the syscolumns table which identifies whether a referenced column is not updatable because it set up to auto increment. Thanks.Check out syscolumns in bol. The value is stored in status as hex 0x80 or 128 (decimal) as a bit flag. Also, you might be able to use the colstat field in syscolumns (1 = identity) but I have not found supported documentation - which means it may be that today but not tomorrow.|||Q1 How do I programmatically identify whether a column is set up to automatically increment?
I am looking for a field in the syscolumns table which identifies whether a referenced column is not updatable because it set up to auto increment. Thanks.

A1 Use sp_columns (check the Type_Name result set column). For example:

exec sp_columns
@.table_name = 'YourTable',
@.column_name = 'MysteryColumn'

You could also use the third result set of sp_help (or sp_columns more generally):

USE pubs
EXEC sp_help jobs
EXEC sp_columns jobs
EXEC sp_columns @.table_name = 'jobs', @.column_name = 'job_id'

-- compare to (no identity column)
EXEC sp_help authors
EXEC sp_columns authors|||The sp_columns/sp_help just uses the syscolumns database - so if you are looking for a specific answer use the bit flag from syscolumns. Using sp_columns/sp_help adds another layer of complexity that you can pull directly from syscolumns. As a matter of fact, sp_help uses the colstat column to determine an identity column - again this is undocumentated but used with sp_help.

You can use the following as a template:

select a.name, b.name from syscolumns as a inner join sysobjects as b on a.id = b.id where a.status & 0x80 > 0

It will return the column name and object name that has an identity field. You will need to fine tune this for you scenario - but you will be able to return a count or other specific information directly.

Good luck.|||RE:
The sp_columns/sp_help just uses the syscolumns database - so if you are looking for a specific answer use the bit flag from syscolumns. Using sp_columns/sp_help adds another layer of complexity that you can pull directly from syscolumns. As a matter of fact, sp_help uses the colstat column to determine an identity column - again this is undocumentated but used with sp_help.

Selecting directly from system tables, (and not isolating user stored procedurees / applications from changes to underlying system tables in any way) may add multiple layers of "complexity" (in the form of maintenance checks and tasks to perform with every Sql Server service pack), as well. Such practices have also resulted in worse, (in the form of addressing / correcting corrupt data, and troubleshooting stored procedurees / applications that "mysteriously" began to malfunction and generate corrupt data and / or corrupt existing data), following the application of Sql Server upgrades that alter system tables.

Adding a layer of abstraction is exactly the point. Doing so in an organized manner often provides significant benefits in regard to minimizing support and maintenance resource use, and costs (especially in relation to addressing and correcting corrupt data, which may cause a business irreparable damage). If selecting directly from system tables is unavoidable (or using sp_columns/sp_help adds "too much" complexity); consider centralizing maintenance issues by providing your own private level of abstraction e.g.(sp_TableIdentityColumns).

Specifically: Consider creating your own user special stored procedures / functions (that select directly from system tables) and calling them in any other user stored procedures and applications. That way, (when Sql Server upgrades, service pack, or hot fix changes alter the underlying system tables radically), you need only change a few user special stored procedures / functions (rather than every procedure / application that calls / uses them).|||Its always recommended to lookup at INFORMATION SCHEMA VIEWS and not to query against SYSTEM tables. REfer to Books online for more information .

HTH
Originally posted by RickLambert
How do I programmatically identify whether a column is set up to automatically increment? I am looking for a field in the syscolumns table which identifies whether a referenced column is not updatable because it set up to auto increment. Thanks.|||RE: Its always recommended to lookup at INFORMATION SCHEMA VIEWS and not to query against SYSTEM tables. REfer to Books online for more information .
HTH

That would normally have been one reccomendation / suggestion; but, I do not know of any Information_Schema View (COLUMNS, TABLES, and TABLE_CONSTRAINTS, etc.) that provides identity column information?

Could you please share where identity column information is available in the Information_Schema views?? (If it is there, I would appreciate knowing where it may be found. - Thanks.)

Information_Schema views:

CHECK_CONSTRAINTS
COLUMNS
COLUMN_DOMAIN_USAGE
COLUMN_PRIVILEGES
CONSTRAINT_COLUMN_USAGE
CONSTRAINT_TABLE_USAGE
DOMAINS
DOMAIN_CONSTRAINTS
KEY_COLUMN_USAGE
PARAMETERS
REFERENTIAL_CONSTRAINTS
ROUTINES
ROUTINE_COLUMNS
SCHEMATA
TABLES
TABLE_CONSTRAINTS
TABLE_PRIVILEGES
VIEWS
VIEW_COLUMN_USAGE
VIEW_TABLE_USAGE|||Thank you everyone for your response. This web site is a most impressive resource! So, I think I will use the ColStat=1, since this appears to be the most straightforward approach and my paranoia level is not very high. My objective is to create a view which contains a list of all columns and their characteristics, for the purpose of programmatically building insert, update, and delete stored procedures. Thanks again!|||I am curious if you are accessing this data exclusively in sql server or are you going to have an application access this data - say through visual basic or c++. Also, is it possible that you would like to have this functionality accessible to all databases or will it be isolated to one ?|||Hi rnealejr:

I am using an MS Access Data Project with SQL Server data to build SQL Server-specific stored procedures. However stored procedure naming and the parameters passed will remain constant regardless of the underlying database.

So I could use a similar approach to create Oracle stored procedures which would be referenced identically in code; just the connect string would change.

Similarly, the process of building the stored procedures is not hard-coded. A table contains the db-specific syntax for each type of stored procedure (insert-update-delete). Then this is is used by the sp-building routine which uses ADO to cycle through each of the rows in the view containing all the column characteristics of every table of the current database.

By the way, is there an easy way to determine the unique identifier of each table?

-RAL|||Since you are using ADO you could use the information from the provider and determine whether a column is an identity column (know that with ADO the provider has a wealth of information that may not be obvious) - but that may not be appropriate in this case. How do you compile these dynamic stored procedures ? Or is it just the syntax you are dynamically creating ? Can you give an example of the process ?

My other suggestion is to create an Information_Schema view - this would allow you to store the view in one location but run it in the context of the any (current) database.

Are you referring to the uniqueidentifier data type ?|||You can use the Information_Schema.columns view. Look under the DATA_TYPE column.|||Originally posted by rnealejr
Since you are using ADO you could use the information from the provider and determine whether a column is an identity column (know that with ADO the provider has a wealth of information that may not be obvious) - but that may not be appropriate in this case. How do you compile these dynamic stored procedures ? Or is it just the syntax you are dynamically creating ? Can you give an example of the process ?

My other suggestion is to create an Information_Schema view - this would allow you to store the view in one location but run it in the context of the any (current) database.

Are you referring to the uniqueidentifier data type ?

By unique identifier I meant primary key. I think this can be extracted using a view joining sysObjects-sysIndexes-sysIndexKeys.

Not sure how ADO would know how to build these stored procedures without reference to an appropriate view.

Here is an example of the syntax stored in the table referenced by the ADO code:

Create Procedure s_Insert_<<TableName>>
(
<<ParameterList>>
)

As
set nocount on

Insert Into dbo.<<TableName>> (
<<FieldList>>

) Values (

<<ValueList>>
)
return|||Originally posted by rnealejr
You can use the Information_Schema.columns view. Look under the DATA_TYPE column.

I am not familiar with how to access this programmatically.|||RE:
By unique identifier I meant primary key. I think this can be extracted using a view joining sysObjects-sysIndexes-sysIndexKeys.
...
Information_Schema.columns view. Look under the DATA_TYPE column.
I am not familiar with how to access this programmatically.


Q1 [How may one identify ALL unique (and candidate keys, including compound keys) columns in a table?]
A1 MS Sql Server 2k and earlier implement unique columns at the DBMS level via indices. (Looking at a table object's indices is therefore a good way to find columns that are implemented as such using built in DBMS methods. However privately maintained unique columns that do not use built in DBMS functionality to guarantee unique row values may not necessarily be identifiable using this approach.)

An example (to identify ALL unique columns (candidate keys, including compound keys):
Use Northwind
Go
exec sp_HelpIndex @.objname = 'Orders'
---

Q2 [RE: The Information_Schema.columns view; I am not familiar with how to access this programmatically?]
A2 For an example, run:

Use Northwind
Go
Select TABLE_NAME, COLUMN_NAME, DATA_TYPE
From [Information_Schema].[columns]
Where
[TABLE_NAME] = 'Orders'|||Thanx, DBA!|||Thanx, DBA!
You are welcome; hopefully some of it will help you create more robust apps.|||In a similar question, how do I find out if there are any table(s) that using IDENTITY column or numerical column as an IDENTITY, and using it to figure out if the column will reach the Max. value (like the SSN) very soon ?

Thanks|||You can use the following:

DBCC CHECKIDENT ('table_name', NORESEED)

What do you mean by max value - 2,147,483,647 ? Which data type are you using for your identity int or bigint (ss2k only) ?|||or use IDENT_CURRENT('table_name')|||Thanks rnealejr. I am aware of the DBCC CHECKIDENT and IDENT_CURRENT function, but what if the column is NOT employed the IDENTITY but other numeric data type (int or bigint) ? For example, the PurchaseOrder column is using INT as data type and it started at seed 2,000,000,000 (2 billion), and increment by 1000 ... I wanted to find out if such column is exists and how soon it will reach the Max value of INT.

Thanks|||So you have other columns that are not identity columns but numeric columns and need to check and see if you are near the cap for that data type - is this an accurate picture ?|||You got that 100% corrected. :-)

Thanks rnealejr|||So you have 2 options:

1. Search through every table for int/bigints and compare against max value.
2. Create a table of only the columns you need to check.

So which one do you want to do ?|||I can find the IDENT column with this script:

select b.name 'Table Name', a.name 'Column Name'
from syscolumns as a inner join sysobjects as b on a.id = b.id
where b.type = 'u'
and a.status & 0x80 > 0

and I needed to resolve the option#1 you described.

Regards with kindly,

Dam234|||It will not matter whether a column is ident or not - you will be searching for all int/bigint which will include identity columns as well.

Let me see what I can scratch up.|||Portions of this may (or may not) exactly address the issue(s).

However, perhaps some of the following may be helpful (if a bit
repetitive):

1) An Identity column in MS Sql Server 2k may be defined using
any of the following types: (filling the range for a numeric / decimal beginning from - 10^38 +1 to 10^38 - 1 would take a while given 1++ )

[bigint]
[int]
[tinyint]
[numeric]
[decimal]

2) For columns that do use built in DBMS functionality a recommendation for finding out information about candidate
keys, including compound keys is to use exec sp_HelpIndex
@.objname = 'TargetTableName'; as MS Sql Server 2k and earlier
implement unique columns at the DBMS level via indices. Looking
at a table object's indices is a means of identifying columns
that are implemented as such using built in DBMS methods.
(Privately maintained unique columns that do not use built in
DBMS functionality to guarantee unique row values may not
necessarily be identifiable using this approach.)

3) For columns that do not use built in DBMS functionality to
guarantee unique row values writing custom functions / stored
procedures may be necessary. This would include columns that are
not DBMS supported Identity columns per se, that are instead
maintained by user created "identity type" functionality. To
determine if such columns are near the limit for the "custom
data type" would obviously depend not only on the current value
and absolute limit of the underlying "type", but also the
private algorithm itself. (A private algorithm may increment,
decrement etc., by different intervals and may or may not
recycle previously used / deleted values and may or may not be
limited to decimal representations, e.g. hex or greater bases could be used.).

4) An example (to identify candidate keys, including compound
keys that DO use built in DBMS methods):
Use Northwind
Go
exec sp_HelpIndex @.objname = 'Orders'

5) A recommended general means for finding out information about DBMS Identity columns is to use sp_columns, and / or sp_help, and /
or as rnealejr has noted, DBCC CHECKIDENT ('table_name', NORESEED)
and / or IDENT_CURRENT('table_name').

For example:

USE pubs
EXEC sp_help jobs
EXEC sp_columns jobs
EXEC sp_columns @.table_name = 'jobs', @.column_name = 'job_id'
Select IDENT_CURRENT('jobs') As 'IdentCurrent'
Go
DBCC CHECKIDENT ('jobs', NORESEED)

6) More specific means for finding out information about DBMS Identity
columns:

If the additional overhead involved (in the form of maintenance)
is acceptable, one may create user special stored procedures /
functions to provide a variety of additional information about
table objects with identity columns. (Similar to
sp_TableIdentityColumnMetaData and
fn_TableIdentityColumnsMetaData posted here, or
sp_TableIdentityColumns and fn_TableIdentityColumns, posted
earlier in this thread.)

Note: When Sql Server upgrades, service pack, or hot fix changes
alter the underlying system tables involved such user special
stored procedures / functions (that select directly from system
tables) may very well require modification to continue to run
and / or return correct result sets.|||Thanks DBA. I already know how to identify IDENT column, the other
numerical columns are the one that I have to deal with.sql

How do I identify the replication generated column(s) in a table

I need to dynamically generate a select command that does not include
replication generated columns. Is there a way to do this? I could use
GetOleDbSchemaTable and filter for column names with "rowguid" but that does
not seem robust to me. Is there a system table or stored procedure that can
help? Dropping a replication subscription and publication removes these
columns so I suspect that the information is available somewhere.
Thanks
Dropping a publication doesn't drop the guid columns added to a merge
publication. As far as I know we can't identify those columns added.
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com .
|||What about something like this:
declare @.mystring varchar(2000)
set @.mystring='select '
select @.mystring=@.mystring+' '+name+', ' From syscolumns where
id=object_id('customers')
and name <>'rowguid'
select @.mystring=substring(@.mystring,1,len(@.mystring)-1)+' from customers'
print @.mystring
Hilary Cotter
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
Looking for a FAQ on Indexing Services/SQL FTS
http://www.indexserverfaq.com
"Kohn" <Kohn@.discussions.microsoft.com> wrote in message
news:915755D4-E2FC-4790-B0E8-6E493DE1BA4F@.microsoft.com...
>I need to dynamically generate a select command that does not include
> replication generated columns. Is there a way to do this? I could use
> GetOleDbSchemaTable and filter for column names with "rowguid" but that
> does
> not seem robust to me. Is there a system table or stored procedure that
> can
> help? Dropping a replication subscription and publication removes these
> columns so I suspect that the information is available somewhere.
> Thanks
>
|||Hi Hilary - unfortunately this doesn't work . We could query for the
rowguid column on the table, but that might already have existed prior to
the replication setup. As far as I can tell there isn't a way of knowing if
the rowguid column is added by the replication setup or by a user
beforehand.
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com .
|||It will work for the majority of the cases.
Hilary Cotter
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
Looking for a FAQ on Indexing Services/SQL FTS
http://www.indexserverfaq.com
"Paul Ibison" <Paul.Ibison@.Pygmalion.Com> wrote in message
news:O$uP0uJNHHA.3424@.TK2MSFTNGP02.phx.gbl...
> Hi Hilary - unfortunately this doesn't work . We could query for the
> rowguid column on the table, but that might already have existed prior to
> the replication setup. As far as I can tell there isn't a way of knowing
> if the rowguid column is added by the replication setup or by a user
> beforehand.
> Cheers,
> Paul Ibison SQL Server MVP, www.replicationanswers.com .
>
|||Another thing to take into account is that replication does not require
the column to be called rowguid. It just requires a column with the
ROWGUIDCOL property set. Maybe that is where you should start looking.
Hilary Cotter wrote:
> What about something like this:
> declare @.mystring varchar(2000)
> set @.mystring='select '
> select @.mystring=@.mystring+' '+name+', ' From syscolumns where
> id=object_id('customers')
> and name <>'rowguid'
> select @.mystring=substring(@.mystring,1,len(@.mystring)-1)+' from customers'
> print @.mystring
>
|||I had a quick look and it seems you have to look for colomns where
syscolumns.colstat = 2. You can also only have one column per table with
the ROWGUIDCOL property set, so you can be pretty sure that is the
column used by replication. So to modify Hilary's query:
declare @.mystring varchar(2000)
set @.mystring='select '
select @.mystring=@.mystring+' '+name+', ' From syscolumns where
id=object_id('customers')
and colstat <> 2
select @.mystring=substring(@.mystring,1,len(@.mystring)-1)+' from
customers'
print @.mystring
JE wrote:[vbcol=seagreen]
> Another thing to take into account is that replication does not require
> the column to be called rowguid. It just requires a column with the
> ROWGUIDCOL property set. Maybe that is where you should start looking.
>
> Hilary Cotter wrote:
|||The information for identifying the column with the rowguid property solves
the problem. My app retrieves the information with the GetOleDbSchemaTable
function (see below).
By the way, rowguid columns created by the wizard are removed when dropping
the publication. I suspect it uses the preserve_rowguidcol column in the
sysmergearticles tables.
cn.Open()
Dim t As DataTable = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns,
New Object() {Nothing, Nothing, TableName, Nothing})
cn.Close()
cn.Dispose()
Dim SelectRows() As DataRow
SelectRows = t.Select("(DATA_TYPE <> 72) AND
(COLUMN_HASDEFAULT=FALSE) AND (COLUMN_HASDEFAULT=False) AND
((ISNULL(COLUMN_DEFAULT,'T')='T') OR
(COLUMN_DEFAULT<>'(newsequentialid())'))")
Dim SelectListStringBuilder As New System.Text.StringBuilder
For Each r As DataRow In SelectRows
SelectListStringBuilder.Append(r.Item("COLUMN_NAME "))
SelectListStringBuilder.Append(",")
Next
SelectListStringBuilder.Length -= 1
Debug.WriteLine(SelectListStringBuilder.ToString)
Thanks for the help

How do I identify dependencies before adding a column to a table?

I need to add a new column to a frequently used table in Production.
I want to make sure that the addition of the column does not break any
existing code in stored procs or triggers.
I can run sp_depends to identify potential problems but I believe this
system procedure is not entirely reliable.
Is the best approach a text search of sysobjects/syscomments to identify
dependencies? And other than "SELECT *," what are some things that might
break that I should be looking for?
Thanks
Dave> And other than "SELECT *," what are some things that might
> break that I should be looking for?
Off the top of my head, there is at least one other thing. The following
will now fail with incorrect number of columns specified:
INSERT table VALUES(blah, blah, blah)
--
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/|||In trigger code, the function columns_updated() is positional.
"DaveF" <davef@.comcast.net> wrote in message
news:uNHgPrzwDHA.2784@.tk2msftngp13.phx.gbl...
> I need to add a new column to a frequently used table in Production.
> I want to make sure that the addition of the column does not break any
> existing code in stored procs or triggers.
> I can run sp_depends to identify potential problems but I believe this
> system procedure is not entirely reliable.
> Is the best approach a text search of sysobjects/syscomments to identify
> dependencies? And other than "SELECT *," what are some things that might
> break that I should be looking for?
> Thanks
> Dave
>|||Sp_depends only contains info about objects that existed when you created
the sp... So it is possible that sp_depends does NOT show all sp
dependencies... I generally script out all sps and do a find...
--
Wayne Snyder MCDBA, SQL Server MVP
Computer Education Services Corporation (CESC), Charlotte, NC
(Please respond only to the newsgroups.)
I support the Professional Association for SQL Server
(www.sqlpass.org)
"DaveF" <davef@.comcast.net> wrote in message
news:uNHgPrzwDHA.2784@.tk2msftngp13.phx.gbl...
> I need to add a new column to a frequently used table in Production.
> I want to make sure that the addition of the column does not break any
> existing code in stored procs or triggers.
> I can run sp_depends to identify potential problems but I believe this
> system procedure is not entirely reliable.
> Is the best approach a text search of sysobjects/syscomments to identify
> dependencies? And other than "SELECT *," what are some things that might
> break that I should be looking for?
> Thanks
> Dave
>|||> In trigger code, the function columns_updated() is positional.
True. Though for the benefit of the original poster, code using
columns_updated() would only be affected if you used Enterprise Manager to
inject the column in the middle of the table. If you use ALTER TABLE ...
ADD COLUMN, the ordinal_position is next, so that existing code for
columns_updated should not have any effect...
--
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/|||Thanks to everyone who responded.
I created a stored proc to search the code for potential problems.
This approach helped me find some things that sp_depends did not.
For anyone else who may face this problem, I include the proc below.
Thanks again.
Dave
USE admin
GO
--sample call:
--EXEC checkdepends 'mls', 'select *'
--dbo.checkdepends.PRC
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id =object_id(N'[dbo].[checkdepends]')
and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[checkdepends]
GO
CREATE PROC checkdepends
@.objname varchar(128) --object on which to identify dependencies (e.g.,
table name)
,@.str varchar(60) -- string used to search for dependencies (e.g., SELECT
* )
AS
DECLARE @.objtype varchar(24) --type of object (stored proc, trigger)
,@.c int -- record counter for coursor
,@.i int -- affected records counter
SET @.c = 0
SET @.i = 0
SET @.objname = '%' + @.objname + '%'
SET @.str = '%' + @.str + '%'
SET NOCOUNT ON
--build a table to hold the list of referencing objects (i.e., any db
object that references the target object #objname)
IF OBJECT_ID('tempdb..#refs','u') IS NOT NULL
DROP TABLE #refs
CREATE TABLE #refs
(
objname varchar(128)
,objtype varchar(24)
)
--grab all of the objects that reference the target object in their code
INSERT INTO #refs
SELECT name, xtype FROM sysobjects o JOIN syscomments c ON c.id=o.id WHERE
text LIKE @.objname ORDER BY xtype
SELECT @.i= count(*)
FROM #refs
PRINT 'There are ' + str(@.i) + ' objects referencing ' + @.objname
PRINT ''
--create a table to hold the referencing object's code
IF OBJECT_ID('tempdb..#text','u') IS NOT NULL
DROP TABLE #text
CREATE TABLE #text (rowid int identity, obj_text varchar(8000))
--create a cursor to examine each referencing object in detail
DECLARE curs CURSOR
FOR
SELECT objname, objtype
FROM #refs
FOR READ ONLY
OPEN curs
FETCH NEXT FROM curs
INTO @.objname, @.objtype
WHILE @.@.fetch_status = 0
BEGIN
-- Add the proc code to the table (1 line of code = 1 record)
INSERT #text
EXEC sp_helptext @.objname
--check for the presence of search string within the referencing object's
code
SELECT @.i= count(*)
FROM #text
WHERE obj_text LIKE @.str
IF @.i > 0
BEGIN
PRINT
'+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++'
PRINT str(@.c) + '. ' + @.objname + '. Type = ' + @.objtype
PRINT ''
-- Select from the lines of code that have the string we are looking for
SELECT *
FROM #text
WHERE obj_text LIKE @.str
--empty the table to get ready for another proc
TRUNCATE TABLE #text
END
--increment the counter
SET @.c=@.c+1
FETCH NEXT FROM curs
INTO @.objname, @.objtype
END
CLOSE curs
DEALLOCATE curs|||Note that their still might be another problem, and that is if you have a
stored procedure > 8kb, a column or table name might actually start at
character 7995 and end at character 8012, which means that the result could
be split across separate columns in syscomments.
Might be safer to script the procedures, functions etc. and do a brute force
file-based search instead of using syscomments.
--
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/
"DaveF" <davef@.comcast.net> wrote in message
news:uG1MTR1wDHA.1272@.TK2MSFTNGP12.phx.gbl...
> Thanks to everyone who responded.
> I created a stored proc to search the code for potential problems.
> This approach helped me find some things that sp_depends did not.
> For anyone else who may face this problem, I include the proc below.
> Thanks again.
> Dave
>
> USE admin
> GO
> --sample call:
> --EXEC checkdepends 'mls', 'select *'
> --dbo.checkdepends.PRC
> IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id => object_id(N'[dbo].[checkdepends]')
> and OBJECTPROPERTY(id, N'IsProcedure') = 1)
> DROP PROCEDURE [dbo].[checkdepends]
> GO
> CREATE PROC checkdepends
> @.objname varchar(128) --object on which to identify dependencies (e.g.,
> table name)
> ,@.str varchar(60) -- string used to search for dependencies (e.g.,
SELECT
> * )
> AS
> DECLARE @.objtype varchar(24) --type of object (stored proc, trigger)
> ,@.c int -- record counter for coursor
> ,@.i int -- affected records counter
> SET @.c = 0
> SET @.i = 0
> SET @.objname = '%' + @.objname + '%'
> SET @.str = '%' + @.str + '%'
> SET NOCOUNT ON
> --build a table to hold the list of referencing objects (i.e., any db
> object that references the target object #objname)
> IF OBJECT_ID('tempdb..#refs','u') IS NOT NULL
> DROP TABLE #refs
> CREATE TABLE #refs
> (
> objname varchar(128)
> ,objtype varchar(24)
> )
>
> --grab all of the objects that reference the target object in their code
> INSERT INTO #refs
> SELECT name, xtype FROM sysobjects o JOIN syscomments c ON c.id=o.id
WHERE
> text LIKE @.objname ORDER BY xtype
> SELECT @.i= count(*)
> FROM #refs
> PRINT 'There are ' + str(@.i) + ' objects referencing ' + @.objname
> PRINT ''
>
> --create a table to hold the referencing object's code
> IF OBJECT_ID('tempdb..#text','u') IS NOT NULL
> DROP TABLE #text
> CREATE TABLE #text (rowid int identity, obj_text varchar(8000))
>
> --create a cursor to examine each referencing object in detail
> DECLARE curs CURSOR
> FOR
> SELECT objname, objtype
> FROM #refs
> FOR READ ONLY
> OPEN curs
>
> FETCH NEXT FROM curs
> INTO @.objname, @.objtype
> WHILE @.@.fetch_status = 0
> BEGIN
> -- Add the proc code to the table (1 line of code = 1 record)
> INSERT #text
> EXEC sp_helptext @.objname
> --check for the presence of search string within the referencing
object's
> code
> SELECT @.i= count(*)
> FROM #text
> WHERE obj_text LIKE @.str
> IF @.i > 0
> BEGIN
> PRINT
>
'+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> +++++++++++'
> PRINT str(@.c) + '. ' + @.objname + '. Type = ' + @.objtype
> PRINT ''
> -- Select from the lines of code that have the string we are looking
for
> SELECT *
> FROM #text
> WHERE obj_text LIKE @.str
> --empty the table to get ready for another proc
> TRUNCATE TABLE #text
> END
> --increment the counter
> SET @.c=@.c+1
> FETCH NEXT FROM curs
> INTO @.objname, @.objtype
> END
>
> CLOSE curs
> DEALLOCATE curs
>
>
>|||> be split across separate columns in syscomments.
Err, separate rows/tuples, sorry.
--
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/|||hello Dave,
I think the answer to your problem is simple. Build it. If
you do a complete build of all your source any errors that
your change could cause will be raised. Sounds easy when I
say it like this, however if you check out www.dbghost.com
it show how this can be made very simple.
All other code (exe,dll,asp) is commonly built to find
errors due to dependancy. Database code isn't (generally).
We would like to change this and take the guess work out
of making changes to your database code.
regards,
Mark Baekdal
www.dbghost.com
>--Original Message--
>I need to add a new column to a frequently used table in
Production.
>I want to make sure that the addition of the column does
not break any
>existing code in stored procs or triggers.
>I can run sp_depends to identify potential problems but I
believe this
>system procedure is not entirely reliable.
>Is the best approach a text search of
sysobjects/syscomments to identify
>dependencies? And other than "SELECT *," what are some
things that might
>break that I should be looking for?
>Thanks
>Dave
>
>.
>

Wednesday, March 21, 2012

How do i getting many Rows from a single XML column?

using SQL 2005...

I have a table called training. It has 2 columns ID and data.
The ID column is a INT.
The data column is an XML data type that contains XML looking like the following:
<TrainingRequests>
<TrainingRequest>
<ProgramName>Learn SQL 2005<ProgramName>
<UrgencyLevel>3</UrgencyLevel>
</TrainingRequest>
<TrainingRequest>
<ProgramName>Learn To Walk<ProgramName>
<UrgencyLevel>1</UrgencyLevel>
</TrainingRequest>
<TrainingRequest>
<ProgramName>Learn To Eat<ProgramName>
<UrgencyLevel>1</UrgencyLevel>
</TrainingRequest>
</TrainingRequests>

if we asume that the table has 3 rows with the ID field being 1-3 and all the XML is the same as above.
I'm trying create an SQL statement that outputs the following results

idProgramNameUrgencyLevel
1Learn SQL 20053
1Learn To Walk1
1Learn To Eat1
2Learn SQL 20053
2Learn To Walk1
2Learn To Eat1
3Learn SQL 20053
3Learn To Walk1
3Learn To Eat1
 

please can some one help me?

You will need to use the nodes() to break your xml into multiple rows then CROSS APPLY to that. For example:

Dan

CREATE TABLE #t1(
id int,
data xml
)

INSERT INTO #t1 SELECT 1, '<TrainingRequests>
<TrainingRequest>
<ProgramName>Learn SQL 2005</ProgramName>
<UrgencyLevel>3</UrgencyLevel>
</TrainingRequest>
<TrainingRequest>
<ProgramName>Learn To Walk</ProgramName>
<UrgencyLevel>1</UrgencyLevel>
</TrainingRequest>
<TrainingRequest>
<ProgramName>Learn To Eat</ProgramName>
<UrgencyLevel>1</UrgencyLevel>
</TrainingRequest>
</TrainingRequests>'

INSERT INTO #t1 SELECT 2, '<TrainingRequests>
<TrainingRequest>
<ProgramName>Learn SQL 2005</ProgramName>
<UrgencyLevel>3</UrgencyLevel>
</TrainingRequest>
<TrainingRequest>
<ProgramName>Learn To Walk</ProgramName>
<UrgencyLevel>1</UrgencyLevel>
</TrainingRequest>
<TrainingRequest>
<ProgramName>Learn To Eat</ProgramName>
<UrgencyLevel>1</UrgencyLevel>
</TrainingRequest>
</TrainingRequests>'

INSERT INTO #t1 SELECT 2, '<TrainingRequests>
<TrainingRequest>
<ProgramName>Learn SQL 2005</ProgramName>
<UrgencyLevel>3</UrgencyLevel>
</TrainingRequest>
<TrainingRequest>
<ProgramName>Learn To Walk</ProgramName>
<UrgencyLevel>1</UrgencyLevel>
</TrainingRequest>
<TrainingRequest>
<ProgramName>Learn To Eat</ProgramName>
<UrgencyLevel>1</UrgencyLevel>
</TrainingRequest>
</TrainingRequests>'

SELECT ID, t.c.value('ProgramName[1]', 'NVARCHAR(MAX)') + ' ' + t.c.value('UrgencyLevel[1]', 'NVARCHAR(MAX)')
FROM #t1
CROSS APPLY
#t1.data.nodes('TrainingRequests/TrainingRequest') AS t(c)

|||Thank you, you saved me ripping out the rest of my hair!!!

How do I get to know each column details of a table

How to I get each column details of a table with out opening table in design
mode.> How to I get each column details of a table with out opening table in
> design
> mode.
http://www.aspfaq.com/2177|||Soumya,
In EM, right-click over the table and select "properties". In QA, use stored
procedure sp_help or query the view "information_schema.columns".
Example:
use northwind
go
exec sp_help orders
go
select *
from information_schema.columns
where table_name = 'orders'
order by ordinal_position
go
AMB
"Soumya" wrote:

> How to I get each column details of a table with out opening table in desi
gn
> mode.sql

How do I get the value of a column in the last row of my table?

With out using @.@.identity or count(*) how do i retrieve a value in a column in the last row of my table.

here is the situation. ASP.net project has several sessions open. a user needs to get the value of a column in the last row inserted in a particular table.

Select CallID from Calls where 'it is the last row inserted'

thanks in advance.

you can email me at !cbmorton!@.!gmail.com!

Chris Morton

Hard to get the last row in a relational database. Last means many things: last inserted, last in clustered index, last in another sort, last in a particular index, last in the data page.

Does your table have an Identity column, timestamp, CreatedDate that defaults to getDate()? You need something.

|||

In relational databases the data is by definition unordered, therefore the last data row entered is functionally the same as the first row entered.

That being said, if you have an inserted date/time column you could select from the table where the column equals the max(datetime) value in the table.

How do I get the value of a column in the last row of a table?

With out using @.@.identity or count(*) how do i retrieve a value in a column in the last row of my table.

here is the situation. ASP.net project has several sessions open. a user needs to get the value of a column in the last row inserted in a particular table.

Select CallID from Calls where 'it is the last row inserted'

thanks in advance.

you can email me at !cbmorton!@.!gmail.com!

Chris Morton

Define last row?

maybe this will do what you want but it is kind of dangerous because you might pick up the inserted row from another connection

Select Max(CallID) from Calls

Denis the SQL Menace

http://sqlservercode.blogspot.com/

|||i do want to pick up the last inserted row from another connection|||

There is no "last" row because SQL Server stores data as it comes in within its own storage schema. There is only a last row if you do a order of the query executed. There could be also a last *physical* row if the table includes a clustered index, which is physically ordered.

But if you want to have the last row in a resultsset, you have to order it backwards and get the TOP 1

e.g. SELECT TOP 1 SomeColumn From SomeTable Order by SomeOtherorthesamecolumn DESC

BTW, this is a public newsgroups, as long as you have MSN Alerts activated you will get a notice everytime a new answer arrives. Private communication should only be done if the thread is extended immensly due to details asking and answering back and forth, but also then the answer and the solution should be posted back here, to help other which might be in the same situation with a similar question.

HTH, jens Suessmeyer.

http://www.sqlserver2005.de

How do I get the UserID column value of the User that just has

Hello ML,
Thanks for the reply. May be I am using them in the back ground . All
I do is use controls in the front to get the job done. But I never had
a situation or need to customize these controls and hence had to look
into the aspnetdb database where to make changes inorder to accomplish
my task.
Like I said this is my first time that I have a need to grab the
UserId and push that into another table along with the DelaerShipID. So
I just needed some suggestions on how do I do it.
As a test I Executed the stored proce aspnet_Users_CreateUser and it
returns the @.UserId value here is the output from the Management
Studio...
****************************************
*********************
USE [aspnetdbTest]
GO
DECLARE @.return_value int,
@.UserId uniqueidentifier
EXEC @.return_value = [dbo].[aspnet_Users_CreateUser]
@.ApplicationId = '8203a4f9-995b-4506-aec0-075551d77d02',
@.UserName = N'TestUser',
@.IsUserAnonymous = false,
@.LastActivityDate = N'4/11/2006',
@.UserId = @.UserId OUTPUT
SELECT @.UserId as N'@.UserId'
SELECT 'Return Value' = @.return_value
GO
****************************************
***********************
and the output I got is the @.UserID
'303B2D60-788C-4F96-9930-7E5BA173D165'.
Now my question is :
To get this @.UserID value from the aspnetdb to my Business Layer what
event do I need to use in my code behind page?
Thanks
-LI'm sorry if I sounded harsh. There were no ulterior motives.
You'd better ask this in a more appropriate news group (depending on the
programming language used in your asp code-behind). Basically, you need to
trap the value being returned from the procedure in a local variable in your
asp method by invoking the SQL procedure appropriately. You need to declare
the UserId parameter as an output parameter and assign its value to the loca
l
variable. (Yes, it's obvious that I'm more at home in T-SQL.)
ML
http://milambda.blogspot.com/

How do I get the Table Name the column belongs to in SMO?

Hi guys,

I am writing some sort of tool and I need to get the table a column belongs to.Before you ask for certain reasons too long to explain I need to get it from the column.

I have found out that the following will give me the answer however before I start splitting the string which it could be messy.

is there another way to do it?

My way so far:

?col.Urn.Value Gives:
"Server[@.Name='MYServer']/Database[@.Name='MyDB]/Table[@.Name='UserTable' and @.Schema='dbo']/Column[@.Name='Surname']"

So now .How can I split it to get the table Name? or better is there a cleaner way to do it?

Thanks again for your time in advance

col.Parent will return you a SqlSmoObject which you can cast as a Table (or View).

Hope that helps.

Thanks,
Kuntal

|||That helped and worked thanks.