Showing posts with label primary. Show all posts
Showing posts with label primary. Show all posts

Monday, March 26, 2012

how to get the primary keys and display it horizontally?

sample results: <MRNID=10002><VesselCode=VSL1>

wherein MRNID and VesselCode are primary keys of the table.

What do you mean by "horozontally"

<MRNID=10002><VesselCode=VSL1>

This is horozontally.

<MRNID=10002>
<VesselCode=VSL1>

Would be vertical. Can you be a bit more clear?

|||

do you mean pivoting the table

well sql 2k5 has a pivot keyword

how to get the primary key from the field of the row ive just inserted

I need to insert a row of data and return the value of the primary key id of the row.
I thought that something like this would work


int Key = (int)command.ExecuteScalar();

where command is SqlCommand object.

It doesn't work, maybe I've misunderstood the usage of ExecuteScalar.ExecuteScalar() returns the first row/first column of the resulet set. This should work IF part of the command contains something like SELECT Scope_IDentity() or SELECT @.@.IDENTITY after the insert, and the table has an IDENTITY column.sql

Wednesday, March 21, 2012

How to get the Column Name of primary key of a table?

How to get the Column Name of primary key of a table?
Thanks.
--Using SQL 2005 devFrank Lee wrote:
> How to get the Column Name of primary key of a table?
> Thanks.
> --Using SQL 2005 dev
>
>
This example will return the ordered columns that make up the primary
key of the ContactCreditCard table in the AdventureWorks database:
use AdventureWorks
go
select b.TABLE_NAME, COLUMN_NAME, a.ORDINAL_POSITION
from INFORMATION_SCHEMA.KEY_COLUMN_USAGE a join
INFORMATION_SCHEMA.TABLE_CONSTRAINTS b on a.constraint_name =
b.constraint_name
where b.CONSTRAINT_TYPE = 'PRIMARY KEY' and b.TABLE_NAME =
'ContactCreditCard'
order by b.TABLE_NAME, a.ORDINAL_POSITION
The results will return all of the fields that make up the primary key:
TABLE_NAME COLUMN_NAME ORDINAL_POSITION
ContactCreditCard ContactID 1
ContactCreditCard CreditCardID 2|||You might find this procedure as a useful starting point, sorry about the
formatting. One thing I know it doesn't take into account is compound
*foreign* keys. This was developed for a system that doesn't have any of
those...
Basically, this will show every *user* table in your database, whether the
column is in the primary key or not, the name of the column, the type (as
well as length or precision/scale where appropriate), whether the column
allows nulls, and the foreign key reference if it exists (again, I only
dealt with single column references).
This exclusively uses the new sys. catalog views and so you do not need to
qualify objects with built-ins like objectproperty('isMsShipped') etc.
There might be a way to eliminate some of the joins, especially if you don't
need all of the information. Just providing you with what I developed in a
pinch for my requirements.
CREATE PROCEDURE dbo.ShowColumnList
AS
BEGIN
SET NOCOUNT ON;
SELECT
Table_Name = object_name(c.Object_id),
In_Key = CASE WHEN keys.Column_Name IS NOT NULL THEN 'Yes' ELSE 'No' END,
Column_Name = c.name,
Type_Name = UPPER(t.name + CASE
WHEN t.name IN ('VARCHAR','NVARCHAR') AND c.Max_Length = -1 THEN '(MAX)'
WHEN t.name IN ('NCHAR','NVARCHAR') THEN '('+RTRIM(c.Max_Length/2)+')'
WHEN t.name IN ('CHAR', 'VARCHAR') THEN '('+RTRIM(c.Max_Length)+')'
WHEN t.name IN ('NUMERIC','DECIMAL') THEN
'('+RTRIM(c.precision)+','+RTRIM(c.scale)+')'
ELSE '' END
+ CASE c.is_identity WHEN 1 THEN ' -- IDENTITY' ELSE '' END),
Allows_Nulls = CASE c.is_nullable WHEN 1 THEN 'Yes' ELSE 'No' END,
Foreign_Key = COALESCE(fkeys.Ref_Table_Name+'.'+fkeys.Ref_Column_Name, '')
FROM
sys.columns c
INNER JOIN
sys.types t
ON
c.system_type_id = t.system_type_id
AND t.name != 'SYSNAME'
INNER JOIN
sys.tables tb
ON
c.object_id = tb.object_id
LEFT OUTER JOIN
(
SELECT
Table_Name = OBJECT_NAME(t.object_id),
Column_Name = c.name
FROM
sys.index_columns ic WITH (NOLOCK)
INNER JOIN
sys.indexes i WITH (NOLOCK)
ON ic.index_id = i.index_id
AND i.object_id = ic.object_id
INNER JOIN
sys.tables t WITH (NOLOCK)
ON i.object_id = t.object_id
INNER JOIN
sys.key_constraints k WITH (NOLOCK)
ON k.name = i.name
AND k.type='PK'
INNER JOIN
sys.columns c WITH (NOLOCK)
ON c.Object_id = t.object_id
AND c.column_id = ic.column_id
) keys
ON
keys.Column_Name = c.Name
AND keys.Table_Name = tb.Name
LEFT OUTER JOIN
(
SELECT
Table_Name = OBJECT_NAME(k.Parent_Object_ID),
Column_Name = c1.name,
Ref_Table_Name = OBJECT_NAME(k.Referenced_Object_ID),
Ref_Column_Name = c2.name
FROM
sys.foreign_keys k WITH (NOLOCK)
INNER JOIN
sys.foreign_key_columns kc WITH (NOLOCK)
ON
k.object_id = kc.constraint_object_id
INNER JOIN
sys.columns c1 WITH (NOLOCK)
ON
c1.object_id = kc.parent_object_id
AND kc.parent_column_id = c1.column_id
INNER JOIN
sys.columns c2 WITH (NOLOCK)
ON
c2.object_id = kc.referenced_object_id
AND kc.referenced_column_id = c2.column_id
) fkeys
ON
fkeys.Column_Name = c.Name
AND fkeys.Table_Name = tb.Name
ORDER BY
OBJECT_NAME(c.object_id),
c.column_id;
END
GO
"Frank Lee" <Reply@.to.newsgroup> wrote in message
news:%23kwAsBQDGHA.916@.TK2MSFTNGP10.phx.gbl...
> How to get the Column Name of primary key of a table?
> Thanks.
> --Using SQL 2005 dev
>
>

Friday, March 9, 2012

How to get Reference from CompositePrimaryKey field ??...

I have one table nameMagazine_Details,it has a composite primary key

Create table Magazine_Details(MagazineTitlevarchar(60),MagazineTypevarchar(20),IssueTypevarchar(25),IssueNumbervarchar(10),Qntyint,Qnty_in_Handint,[Date]datetimeconstraint PK_Magazine_Details_Compositeprimary key(MagazineTitle,IssueNumber))

Another table isMagazine_Issued and i want reference from Magazine_Details table. but i am auable to create foreign key constaraint inMagazine_Issued table.

create table Magazine_Issued(Member_IDvarchar(100),MagazineTitlevarchar(60)references Magazine_Details(MagazineTitle),IssueNumbervarchar(10)references Magazine_Details(IssueNumber),IssueDatedatetime,Magazine_Statusvarchar(10))

Hi,

If you need to create the foreign key constraint, you also need to add the CONSTRAINT clause and constraint name.

create table Magazine_Issued
(
Member_ID varchar(100),
MagazineTitle varchar(60) CONSTRAINT FK_MagazineTitle_Details_Issued FOREIGN KEY (MagazineTitle) references Magazine_Details(MagazineTitle),
IssueNumber varchar(10) CONSTRAINT FK_IssueNumber_Details_Issued FOREIGN KEY (IssueNumber) references Magazine_Details(IssueNumber),
IssueDate datetime,
Magazine_Status varchar(10)
)

|||

after trying to create Magazine_Issued Table following error comes.

primary or candidate keys in the referenced table 'Magazine_Details' that match the referencing column list in the foreign key 'FK_MagazineTitle_Details_Issued'.

Could not create constraint. See previous errors.

|||

miazaidi:

after trying to create Magazine_Issued Table with above script following error comes.

primary or candidate keys in the referenced table 'Magazine_Details' that match the referencing column list in the foreign key 'FK_MagazineTitle_Details_Issued'.

Could not create constraint. See previous errors.

How to get Primary key....plz help!

i'm having problem to get th primary key from d database...
for your information i'm using java to get the primary key...
this is my code...
rs = stt.executeQuery("sp_columns "+table_db+";");
while(rs.next())
{
out.write("\n\n"+rs.getString("COLUMN_NAME"));
out.write(",\t"+rs.getString("TYPE_NAME"));
out.write(",\t"+rs.getString("IS_NULLABLE"));
}

rs = stt.executeQuery("sp_foreignkeys @.table_name = N'table_db';");

but the problem is...
i get this error message...could anyone tell me what's the problem...
java.sql.SQLException: [Microsoft][ODBC SQL Server Driver][SQL Server]Could not
find server 'table_db' in sysservers. Execute sp_addlinkedserver to add th
e server to sysservers.

how do i solve this problem...

thanx to anyone who can help me..... :DWe need to see more code, especially for stt definition. "sysservers" has nothing to do with table_db.|||Connection conn = null;
Connection conn2 = null;
Statement stt = null;
Statement stt2 = null;
ResultSet rs = null;
ResultSet rs2 = null;

String driver = prop.getProperty("driver");
String url = prop.getProperty("URL");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
String database = prop.getProperty("database");
String table_db = prop.getProperty("table");
String output = ""+prop.getProperty("target.folder")+"/" + database + "_" + table_db + ".txt";

System.out.println("Server : "+url);
System.out.println("Database : "+database);
System.out.println("Table : "+table_db);
System.out.println("File : "+output);

try
{
Class.forName(driver);
conn = DriverManager.getConnection(url+database, username, password);
conn2 = DriverManager.getConnection(url+database, username, password);
stt = conn.createStatement();
stt2 = conn.createStatement();
}
catch(Exception e){ System.out.println("Connection : "+e.getMessage()); e.printStackTrace();}

try
{
rs = stt.executeQuery("sp_columns "+table_db+";");
while(rs.next())
{
out.write("\n\n"+rs.getString("COLUMN_NAME"));
out.write(",\t"+rs.getString("TYPE_NAME"));
out.write(",\t"+rs.getString("IS_NULLABLE"));
}
}
catch(Exception g){ System.out.println("Fetch : "+g.getMessage()); g.printStackTrace();}

try
{
rs = stt2.executeQuery("sp_foreignkeys @.table_server = N'Met2Parameters';");
while(rs.next())
{
out.write(",\t"+rs.getString("PKCOLUMN_NAME "+table_db+")"));
}
}
catch(Exception g){ System.out.println("Fetch Primary Key: "+g.getMessage()); g.printStackTrace();}

this is the code that you asked... hope u can help me...|||do you get anything back when executing this:

stt.executeQuery("exec sp_columns "+table_db+";");

or

stt.executeQuery("select @.@.version [version];");|||i dun hav any prob to execute that statement... the prob that i'd got was that sp_foreignkeys statement......
actually i hav discovered the problem... but still can't solve the prob...
nway thanx 4 ur time... i really appreciate it....|||I see. Do you actually have a linked server called 'Met2Parameters'. post back if you need additional help.|||firstly, i'm sori.. i dun evn know wat's the table_server... i thought it was db's table :p ... but luckily i'd found wat's the table server... unfotunately... i can't execute the sp_foriegnkeys bcoz i can't get the permission to get the data... when i check it back.. the table_server dun hav data access... means the server just hav rpc,rpc out,use remote collation ...

i'm just a little bit confused.... when i'm trying to use sp_fkeys pktable_name...
it returns no data...
PKTABLE_QUALIFIER PKTABLE_OWNER PKTABLE_NAME PKCOLUMN_NAME FKTABLE_QUALIFIER FKTABLE_OWNER FKTABLE_NAME FKCOLUMN_NAME KEY_SEQ UPDATE_RULE DELETE_RULE FK_NAME PK_NAME DEFERRABILITY
--------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --- ---- ---- --------------------------------------- --------------------------------------- ----

0 Row(s) affected

is it means that the table in the db dun hav pk n fk.....??
bcoz when i check with winsql(just like ent manager but little features)... it shows the db has pk n fk...
sori... i'm new to this db... i'm alwiz using mysql...
can u giv some tips or idea .... thanx|||sp_foreignkeys is used to get info from a linked server.
sp_fkeys is used to get info from a local table.

here is a quick example for finding the pk.

SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'authors'
AND CONSTRAINT_TYPE = 'PRIMARY KEY'

How to get Primary Key (Columns) of a Table?

I want to get the Primary Key Columns in Arrays by sending a table
name. I am using SQL Server 2000 and I want to make a find utility in VB.net which
will work for all the forms; I have tables with one Primary key and some tables with composite Primary keys.

I used to do this in VB 6 by making a function which fills the Primary Keys in
List Box (I require to fill in list box), now I need to get in array.

Can some one tell me the migration of the following VB 6 Code?

This was written for the MS Access, I need same for SQL Server, I can
not find Table Def and Index Object in VB.net 2003.

Public Sub GetFieldsFromDatabase (ldbDatabase As Database, lsTableName As
String)

Dim lttabDef As TableDef
Dim liCounter As Integer
Dim liLoop As Integer
Dim idxLoop As Index
Dim fldLoop As Field

With ldbDatabase
For Each lttabDef In .TableDefs
If lttabDef.Name = lsTableName Then
liCounter = lttabDef.Fields.Count
For liLoop = 0 To liCounter - 1
cboFieldLists.List(liLoop) = lttabDef.Fields(liLoop).Name
Next liLoop
For Each idxLoop In lttabDef.Indexes
With idxLoop
lblIndexName = .Name
If .Primary Then
liCounter = 0
For Each fldLoop In .Fields
cboPrimaryKeys.List(liCounter) = fldLoop.Name
liCounter = liCounter + 1
Next fldLoop
End If
End With
Next
cboFieldLists.ListIndex = 0
If cboPrimaryKeys.ListCount > 0 Then
cboPrimaryKeys.ListIndex = 0
End If
Exit For
End If
Next
End With
End Sub

SQL Server has a built-in system stored procedure calledsp_primarykeys whichwill return you the primary key information for the table you specify.
USE master
EXEC sp_primarykeys @.table_server = N'LONDON1',
@.table_name = N'Customers',
@.table_catalog = N'Northwind',
@.table_schema = N'dbo'
|||Thanks TmortonSmile [:)]

Wednesday, March 7, 2012

how to get optimized join

Hi Experts,
I have following doubts on join condition
Table 1 primary key (id,sub)
Name id sub marks

xxx 61 maths 45
xxx 61 science 50

another table primary key ( id,language)

id language write
61 english yes
61 Hindi no
Output:
Xxx 61 maths 45 english yes
Xxx 61 maths 45 Hindi no
Xxx 61 science 50 english yes
Xxx 61 science 50 hindi no
how to join these tables to get
every information in 2 rows will it possible

xxx 61 maths 45 English yes
xxx 61 science 50 hindi no

please suggest me to right path
thanking u
please mail to me:nallisalmon@.yahoo.co.in


I don′t see the logic which one has to be excluded from the output results ? Is it just randomly or is there a deeper logic implemented ?

HTH, Jens K. Suessmeyer.

http://www.sqlserver2005.de

How to get nextval while inserting a row to database

I try to make something or set an option, which would generate next values of the id of some table (id is primary key) while inserting a row to the table. I used once a sequence for Oracle database and wonder if there is something similar in .Net for "standard" database (Add new item -> SQL Database). I'm using SqlDataSources.

Is Repeater a component that would be useful here? Or shall i write a function that would generate ids manually?

Thanks in advance

I think what you want is an IDENTITY column. Here's a simple article with exampleshttp://www.databasejournal.com/features/mssql/article.php/3307541 and here's the more detailed stuff from MSDN http://msdn2.microsoft.com/en-us/library/aa933196(SQL.80).aspx

|||

Yes, it works now! I didn't noticed 'Column properties' in table definition ^_^

That was exactly what i was looking for - thanks!

Friday, February 24, 2012

How to get list of backup log files from msdb of standby server?

How do we retrieve log file names of primary backup from msdb of
standby database?
In case of primary server unavailable, I need to get the logfile names
from standby server for disater recovery test.
Thanks in advance
Tram
Msdb..backupfile gives you a list of data/log files that are backed up.
For logshipping, take a look at msdb..log_shipping_plan_databases.
-oj
"tram" <tram_e@.hotmail.com> wrote in message
news:1120079449.879078.169120@.o13g2000cwo.googlegr oups.com...
> How do we retrieve log file names of primary backup from msdb of
> standby database?
> In case of primary server unavailable, I need to get the logfile names
> from standby server for disater recovery test.
> Thanks in advance
> Tram
>

How to get list of backup log files from msdb of standby server?

How do we retrieve log file names of primary backup from msdb of
standby database?
In case of primary server unavailable, I need to get the logfile names
from standby server for disater recovery test.
Thanks in advance
TramMsdb..backupfile gives you a list of data/log files that are backed up.
For logshipping, take a look at msdb..log_shipping_plan_databases.
-oj
"tram" <tram_e@.hotmail.com> wrote in message
news:1120079449.879078.169120@.o13g2000cwo.googlegroups.com...
> How do we retrieve log file names of primary backup from msdb of
> standby database?
> In case of primary server unavailable, I need to get the logfile names
> from standby server for disater recovery test.
> Thanks in advance
> Tram
>

How to get list of backup log files from msdb of standby server?

How do we retrieve log file names of primary backup from msdb of
standby database?
In case of primary server unavailable, I need to get the logfile names
from standby server for disater recovery test.
Thanks in advance
TramMsdb..backupfile gives you a list of data/log files that are backed up.
For logshipping, take a look at msdb..log_shipping_plan_databases.
--
-oj
"tram" <tram_e@.hotmail.com> wrote in message
news:1120079449.879078.169120@.o13g2000cwo.googlegroups.com...
> How do we retrieve log file names of primary backup from msdb of
> standby database?
> In case of primary server unavailable, I need to get the logfile names
> from standby server for disater recovery test.
> Thanks in advance
> Tram
>

How to get indexes?

I want to get a list of indexes for a certain table. I like the
sp_helpindex [table_name], but it also returns the primary key index.
How can I get what sp_helpindex returns without the primary key index?
Hi,
Query either SYSINDEXES table or use sp_help <tablename>
Thanks
Hari
SQL Server MVP
"Frank Rizzo" <none@.none.com> wrote in message
news:upXtVEmvFHA.3756@.tk2msftngp13.phx.gbl...
>I want to get a list of indexes for a certain table. I like the
>sp_helpindex [table_name], but it also returns the primary key index. How
>can I get what sp_helpindex returns without the primary key index?
|||I have created one procedure named "Proc_helpindex_without_pk". 99%
code is copied from sp_helpindex procedure and i added 1% piece of code
to meet your requirments.
Do not update sql server system tables and system procedure.
The Customizied Code is as follows.
create proc Proc_helpindex_without_pk
@.objname nvarchar(776)-- the table to check for indexes
as
-- PRELIM
set nocount on
declare @.objid int,-- the object id of the table
@.indid smallint,-- the index id of an index
@.groupid smallint, -- the filegroup id of an index
@.indname sysname,
@.groupname sysname,
@.status int,
@.keys nvarchar(2126),--Length
(16*max_identifierLength)+(15*2)+(16*3)
@.dbnamesysname
-- Check to see that the object names are local to the current
database.
select @.dbname = parsename(@.objname,3)
if @.dbname is not null and @.dbname <> db_name()
begin
raiserror(15250,-1,-1)
return (1)
end
-- Check to see the the table exists and initialize @.objid.
select @.objid = object_id(@.objname)
if @.objid is NULL
begin
select @.dbname=db_name()
raiserror(15009,-1,-1,@.objname,@.dbname)
return (1)
end
-- OPEN CURSOR OVER INDEXES (skip stats: bug shiloh_51196)
declare ms_crs_ind cursor local static for
select indid, groupid, name, status from sysindexes
where id = @.objid and indid > 0 and indid < 255 and (status & 64)=0
and name not in (select constraint_name
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where table_name = object_name(@.objid) and
constraint_type = 'primary key')
order by indid
open ms_crs_ind
fetch ms_crs_ind into @.indid, @.groupid, @.indname, @.status
-- IF NO INDEX, QUIT
if @.@.fetch_status < 0
begin
deallocate ms_crs_ind
raiserror(15472,-1,-1) --'Object does not have any indexes.'
return (0)
end
-- create temp table
create table #spindtab
(
index_namesysnamecollate database_default NOT NULL,
statsint,
groupnamesysname collate database_default NOT NULL,
index_keysnvarchar(2126)collate database_default NOT NULL -- see
@.keys above for length descr
)
-- Now check out each index, figure out its type and keys and
--save the info in a temporary table that we'll print out at the end.
while @.@.fetch_status >= 0
begin
-- First we'll figure out what the keys are.
declare @.i int, @.thiskey nvarchar(131) -- 128+3
select @.keys = index_col(@.objname, @.indid, 1), @.i = 2
if (indexkey_property(@.objid, @.indid, 1, 'isdescending') = 1)
select @.keys = @.keys + '(-)'
select @.thiskey = index_col(@.objname, @.indid, @.i)
if ((@.thiskey is not null) and (indexkey_property(@.objid, @.indid, @.i,
'isdescending') = 1))
select @.thiskey = @.thiskey + '(-)'
while (@.thiskey is not null )
begin
select @.keys = @.keys + ', ' + @.thiskey, @.i = @.i + 1
select @.thiskey = index_col(@.objname, @.indid, @.i)
if ((@.thiskey is not null) and (indexkey_property(@.objid, @.indid,
@.i, 'isdescending') = 1))
select @.thiskey = @.thiskey + '(-)'
end
select @.groupname = groupname from sysfilegroups where groupid =
@.groupid
-- INSERT ROW FOR INDEX
insert into #spindtab values (@.indname, @.status, @.groupname, @.keys)
-- Next index
fetch ms_crs_ind into @.indid, @.groupid, @.indname, @.status
end
deallocate ms_crs_ind
-- SET UP SOME CONSTANT VALUES FOR OUTPUT QUERY
declare @.empty varchar(1) select @.empty = ''
declare @.des1varchar(35),-- 35 matches spt_values
@.des2varchar(35),
@.des4varchar(35),
@.des32varchar(35),
@.des64varchar(35),
@.des2048varchar(35),
@.des4096varchar(35),
@.des8388608varchar(35),
@.des16777216varchar(35)
select @.des1 = name from master.dbo.spt_values where type = 'I' and
number = 1
select @.des2 = name from master.dbo.spt_values where type = 'I' and
number = 2
select @.des4 = name from master.dbo.spt_values where type = 'I' and
number = 4
select @.des32 = name from master.dbo.spt_values where type = 'I' and
number = 32
select @.des64 = name from master.dbo.spt_values where type = 'I' and
number = 64
select @.des2048 = name from master.dbo.spt_values where type = 'I' and
number = 2048
select @.des4096 = name from master.dbo.spt_values where type = 'I' and
number = 4096
select @.des8388608 = name from master.dbo.spt_values where type = 'I'
and number = 8388608
select @.des16777216 = name from master.dbo.spt_values where type = 'I'
and number = 16777216
-- DISPLAY THE RESULTS
select
'index_name' = index_name,
'index_description' = convert(varchar(210), --bits 16 off, 1, 2,
16777216 on, located on group
case when (stats & 16)<>0 then 'clustered' else 'nonclustered' end
+ case when (stats & 1)<>0 then ', '+@.des1 else @.empty end
+ case when (stats & 2)<>0 then ', '+@.des2 else @.empty end
+ case when (stats & 4)<>0 then ', '+@.des4 else @.empty end
+ case when (stats & 64)<>0 then ', '+@.des64 else case when (stats
& 32)<>0 then ', '+@.des32 else @.empty end end
+ case when (stats & 2048)<>0 then ', '+@.des2048 else @.empty end
+ case when (stats & 4096)<>0 then ', '+@.des4096 else @.empty end
+ case when (stats & 8388608)<>0 then ', '+@.des8388608 else @.empty
end
+ case when (stats & 16777216)<>0 then ', '+@.des16777216 else
@.empty end
+ ' located on ' + groupname),
'index_keys' = index_keys
from #spindtab
order by index_name
return (0) -- sp_helpindex
exec Proc_helpindex_without_pk 'authors'
try. all the best
|||Thank you. This is great.
Praveen wrote:

>I have created one procedure named "Proc_helpindex_without_pk". 99%
>code is copied from sp_helpindex procedure and i added 1% piece of code
>to meet your requirments.
>Do not update sql server system tables and system procedure.
>The Customizied Code is as follows.
>create proc Proc_helpindex_without_pk
>@.objname nvarchar(776)-- the table to check for indexes
>as
>-- PRELIM
>set nocount on
>declare @.objid int,-- the object id of the table
>@.indid smallint,-- the index id of an index
>@.groupid smallint, -- the filegroup id of an index
>@.indname sysname,
>@.groupname sysname,
>@.status int,
>@.keys nvarchar(2126),--Length
>(16*max_identifierLength)+(15*2)+(16*3)
>@.dbnamesysname
>-- Check to see that the object names are local to the current
>database.
>select @.dbname = parsename(@.objname,3)
>if @.dbname is not null and @.dbname <> db_name()
>begin
>raiserror(15250,-1,-1)
>return (1)
>end
>-- Check to see the the table exists and initialize @.objid.
>select @.objid = object_id(@.objname)
>if @.objid is NULL
>begin
>select @.dbname=db_name()
>raiserror(15009,-1,-1,@.objname,@.dbname)
>return (1)
>end
>-- OPEN CURSOR OVER INDEXES (skip stats: bug shiloh_51196)
>declare ms_crs_ind cursor local static for
>select indid, groupid, name, status from sysindexes
>where id = @.objid and indid > 0 and indid < 255 and (status & 64)=0
>and name not in (select constraint_name
> from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
> where table_name = object_name(@.objid) and
> constraint_type = 'primary key')
>order by indid
>open ms_crs_ind
>fetch ms_crs_ind into @.indid, @.groupid, @.indname, @.status
>-- IF NO INDEX, QUIT
>if @.@.fetch_status < 0
>begin
>deallocate ms_crs_ind
>raiserror(15472,-1,-1) --'Object does not have any indexes.'
>return (0)
>end
>-- create temp table
>create table #spindtab
>(
>index_namesysnamecollate database_default NOT NULL,
>statsint,
>groupnamesysname collate database_default NOT NULL,
>index_keysnvarchar(2126)collate database_default NOT NULL -- see
>@.keys above for length descr
>)
>-- Now check out each index, figure out its type and keys and
>--save the info in a temporary table that we'll print out at the end.
>while @.@.fetch_status >= 0
>begin
>-- First we'll figure out what the keys are.
>declare @.i int, @.thiskey nvarchar(131) -- 128+3
>select @.keys = index_col(@.objname, @.indid, 1), @.i = 2
>if (indexkey_property(@.objid, @.indid, 1, 'isdescending') = 1)
>select @.keys = @.keys + '(-)'
>select @.thiskey = index_col(@.objname, @.indid, @.i)
>if ((@.thiskey is not null) and (indexkey_property(@.objid, @.indid, @.i,
>'isdescending') = 1))
>select @.thiskey = @.thiskey + '(-)'
>while (@.thiskey is not null )
>begin
>select @.keys = @.keys + ', ' + @.thiskey, @.i = @.i + 1
>select @.thiskey = index_col(@.objname, @.indid, @.i)
>if ((@.thiskey is not null) and (indexkey_property(@.objid, @.indid,
>@.i, 'isdescending') = 1))
>select @.thiskey = @.thiskey + '(-)'
>end
>select @.groupname = groupname from sysfilegroups where groupid =
>@.groupid
>-- INSERT ROW FOR INDEX
>insert into #spindtab values (@.indname, @.status, @.groupname, @.keys)
>-- Next index
>fetch ms_crs_ind into @.indid, @.groupid, @.indname, @.status
>end
>deallocate ms_crs_ind
>-- SET UP SOME CONSTANT VALUES FOR OUTPUT QUERY
>declare @.empty varchar(1) select @.empty = ''
>declare @.des1varchar(35),-- 35 matches spt_values
>@.des2varchar(35),
>@.des4varchar(35),
>@.des32varchar(35),
>@.des64varchar(35),
>@.des2048varchar(35),
>@.des4096varchar(35),
>@.des8388608varchar(35),
>@.des16777216varchar(35)
>select @.des1 = name from master.dbo.spt_values where type = 'I' and
>number = 1
>select @.des2 = name from master.dbo.spt_values where type = 'I' and
>number = 2
>select @.des4 = name from master.dbo.spt_values where type = 'I' and
>number = 4
>select @.des32 = name from master.dbo.spt_values where type = 'I' and
>number = 32
>select @.des64 = name from master.dbo.spt_values where type = 'I' and
>number = 64
>select @.des2048 = name from master.dbo.spt_values where type = 'I' and
>number = 2048
>select @.des4096 = name from master.dbo.spt_values where type = 'I' and
>number = 4096
>select @.des8388608 = name from master.dbo.spt_values where type = 'I'
>and number = 8388608
>select @.des16777216 = name from master.dbo.spt_values where type = 'I'
>and number = 16777216
>-- DISPLAY THE RESULTS
>select
>'index_name' = index_name,
>'index_description' = convert(varchar(210), --bits 16 off, 1, 2,
>16777216 on, located on group
>case when (stats & 16)<>0 then 'clustered' else 'nonclustered' end
>+ case when (stats & 1)<>0 then ', '+@.des1 else @.empty end
>+ case when (stats & 2)<>0 then ', '+@.des2 else @.empty end
>+ case when (stats & 4)<>0 then ', '+@.des4 else @.empty end
>+ case when (stats & 64)<>0 then ', '+@.des64 else case when (stats
>& 32)<>0 then ', '+@.des32 else @.empty end end
>+ case when (stats & 2048)<>0 then ', '+@.des2048 else @.empty end
>+ case when (stats & 4096)<>0 then ', '+@.des4096 else @.empty end
>+ case when (stats & 8388608)<>0 then ', '+@.des8388608 else @.empty
>end
>+ case when (stats & 16777216)<>0 then ', '+@.des16777216 else
>@.empty end
>+ ' located on ' + groupname),
>'index_keys' = index_keys
>from #spindtab
>order by index_name
>
>return (0) -- sp_helpindex
>--
>exec Proc_helpindex_without_pk 'authors'
>try. all the best
>
>

How to get indexes?

I want to get a list of indexes for a certain table. I like the
sp_helpindex [table_name], but it also returns the primary key index.
How can I get what sp_helpindex returns without the primary key index?Hi,
Query either SYSINDEXES table or use sp_help <tablename>
Thanks
Hari
SQL Server MVP
"Frank Rizzo" <none@.none.com> wrote in message
news:upXtVEmvFHA.3756@.tk2msftngp13.phx.gbl...
>I want to get a list of indexes for a certain table. I like the
>sp_helpindex [table_name], but it also returns the primary key index. How
>can I get what sp_helpindex returns without the primary key index?|||I have created one procedure named "Proc_helpindex_without_pk". 99%
code is copied from sp_helpindex procedure and i added 1% piece of code
to meet your requirments.
Do not update sql server system tables and system procedure.
The Customizied Code is as follows.
create proc Proc_helpindex_without_pk
@.objname nvarchar(776) -- the table to check for indexes
as
-- PRELIM
set nocount on
declare @.objid int, -- the object id of the table
@.indid smallint, -- the index id of an index
@.groupid smallint, -- the filegroup id of an index
@.indname sysname,
@.groupname sysname,
@.status int,
@.keys nvarchar(2126), --Length
(16*max_identifierLength)+(15*2)+(16*3)
@.dbname sysname
-- Check to see that the object names are local to the current
database.
select @.dbname = parsename(@.objname,3)
if @.dbname is not null and @.dbname <> db_name()
begin
raiserror(15250,-1,-1)
return (1)
end
-- Check to see the the table exists and initialize @.objid.
select @.objid = object_id(@.objname)
if @.objid is NULL
begin
select @.dbname=db_name()
raiserror(15009,-1,-1,@.objname,@.dbname)
return (1)
end
-- OPEN CURSOR OVER INDEXES (skip stats: bug shiloh_51196)
declare ms_crs_ind cursor local static for
select indid, groupid, name, status from sysindexes
where id = @.objid and indid > 0 and indid < 255 and (status & 64)=0
and name not in (select constraint_name
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where table_name = object_name(@.objid) and
constraint_type = 'primary key')
order by indid
open ms_crs_ind
fetch ms_crs_ind into @.indid, @.groupid, @.indname, @.status
-- IF NO INDEX, QUIT
if @.@.fetch_status < 0
begin
deallocate ms_crs_ind
raiserror(15472,-1,-1) --'Object does not have any indexes.'
return (0)
end
-- create temp table
create table #spindtab
(
index_name sysname collate database_default NOT NULL,
stats int,
groupname sysname collate database_default NOT NULL,
index_keys nvarchar(2126) collate database_default NOT NULL -- see
@.keys above for length descr
)
-- Now check out each index, figure out its type and keys and
-- save the info in a temporary table that we'll print out at the end.
while @.@.fetch_status >= 0
begin
-- First we'll figure out what the keys are.
declare @.i int, @.thiskey nvarchar(131) -- 128+3
select @.keys = index_col(@.objname, @.indid, 1), @.i = 2
if (indexkey_property(@.objid, @.indid, 1, 'isdescending') = 1)
select @.keys = @.keys + '(-)'
select @.thiskey = index_col(@.objname, @.indid, @.i)
if ((@.thiskey is not null) and (indexkey_property(@.objid, @.indid, @.i,
'isdescending') = 1))
select @.thiskey = @.thiskey + '(-)'
while (@.thiskey is not null )
begin
select @.keys = @.keys + ', ' + @.thiskey, @.i = @.i + 1
select @.thiskey = index_col(@.objname, @.indid, @.i)
if ((@.thiskey is not null) and (indexkey_property(@.objid, @.indid,
@.i, 'isdescending') = 1))
select @.thiskey = @.thiskey + '(-)'
end
select @.groupname = groupname from sysfilegroups where groupid =@.groupid
-- INSERT ROW FOR INDEX
insert into #spindtab values (@.indname, @.status, @.groupname, @.keys)
-- Next index
fetch ms_crs_ind into @.indid, @.groupid, @.indname, @.status
end
deallocate ms_crs_ind
-- SET UP SOME CONSTANT VALUES FOR OUTPUT QUERY
declare @.empty varchar(1) select @.empty = ''
declare @.des1 varchar(35), -- 35 matches spt_values
@.des2 varchar(35),
@.des4 varchar(35),
@.des32 varchar(35),
@.des64 varchar(35),
@.des2048 varchar(35),
@.des4096 varchar(35),
@.des8388608 varchar(35),
@.des16777216 varchar(35)
select @.des1 = name from master.dbo.spt_values where type = 'I' and
number = 1
select @.des2 = name from master.dbo.spt_values where type = 'I' and
number = 2
select @.des4 = name from master.dbo.spt_values where type = 'I' and
number = 4
select @.des32 = name from master.dbo.spt_values where type = 'I' and
number = 32
select @.des64 = name from master.dbo.spt_values where type = 'I' and
number = 64
select @.des2048 = name from master.dbo.spt_values where type = 'I' and
number = 2048
select @.des4096 = name from master.dbo.spt_values where type = 'I' and
number = 4096
select @.des8388608 = name from master.dbo.spt_values where type = 'I'
and number = 8388608
select @.des16777216 = name from master.dbo.spt_values where type = 'I'
and number = 16777216
-- DISPLAY THE RESULTS
select
'index_name' = index_name,
'index_description' = convert(varchar(210), --bits 16 off, 1, 2,
16777216 on, located on group
case when (stats & 16)<>0 then 'clustered' else 'nonclustered' end
+ case when (stats & 1)<>0 then ', '+@.des1 else @.empty end
+ case when (stats & 2)<>0 then ', '+@.des2 else @.empty end
+ case when (stats & 4)<>0 then ', '+@.des4 else @.empty end
+ case when (stats & 64)<>0 then ', '+@.des64 else case when (stats
& 32)<>0 then ', '+@.des32 else @.empty end end
+ case when (stats & 2048)<>0 then ', '+@.des2048 else @.empty end
+ case when (stats & 4096)<>0 then ', '+@.des4096 else @.empty end
+ case when (stats & 8388608)<>0 then ', '+@.des8388608 else @.empty
end
+ case when (stats & 16777216)<>0 then ', '+@.des16777216 else
@.empty end
+ ' located on ' + groupname),
'index_keys' = index_keys
from #spindtab
order by index_name
return (0) -- sp_helpindex
--
exec Proc_helpindex_without_pk 'authors'
try. all the best|||Thank you. This is great.
Praveen wrote:
>I have created one procedure named "Proc_helpindex_without_pk". 99%
>code is copied from sp_helpindex procedure and i added 1% piece of code
>to meet your requirments.
>Do not update sql server system tables and system procedure.
>The Customizied Code is as follows.
>create proc Proc_helpindex_without_pk
> @.objname nvarchar(776) -- the table to check for indexes
>as
> -- PRELIM
> set nocount on
> declare @.objid int, -- the object id of the table
> @.indid smallint, -- the index id of an index
> @.groupid smallint, -- the filegroup id of an index
> @.indname sysname,
> @.groupname sysname,
> @.status int,
> @.keys nvarchar(2126), --Length
>(16*max_identifierLength)+(15*2)+(16*3)
> @.dbname sysname
> -- Check to see that the object names are local to the current
>database.
> select @.dbname = parsename(@.objname,3)
> if @.dbname is not null and @.dbname <> db_name()
> begin
> raiserror(15250,-1,-1)
> return (1)
> end
> -- Check to see the the table exists and initialize @.objid.
> select @.objid = object_id(@.objname)
> if @.objid is NULL
> begin
> select @.dbname=db_name()
> raiserror(15009,-1,-1,@.objname,@.dbname)
> return (1)
> end
> -- OPEN CURSOR OVER INDEXES (skip stats: bug shiloh_51196)
> declare ms_crs_ind cursor local static for
> select indid, groupid, name, status from sysindexes
> where id = @.objid and indid > 0 and indid < 255 and (status & 64)=0
> and name not in (select constraint_name
> from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
> where table_name = object_name(@.objid) and
> constraint_type = 'primary key')
> order by indid
> open ms_crs_ind
> fetch ms_crs_ind into @.indid, @.groupid, @.indname, @.status
> -- IF NO INDEX, QUIT
> if @.@.fetch_status < 0
> begin
> deallocate ms_crs_ind
> raiserror(15472,-1,-1) --'Object does not have any indexes.'
> return (0)
> end
> -- create temp table
> create table #spindtab
> (
> index_name sysname collate database_default NOT NULL,
> stats int,
> groupname sysname collate database_default NOT NULL,
> index_keys nvarchar(2126) collate database_default NOT NULL -- see
>@.keys above for length descr
> )
> -- Now check out each index, figure out its type and keys and
> -- save the info in a temporary table that we'll print out at the end.
> while @.@.fetch_status >= 0
> begin
> -- First we'll figure out what the keys are.
> declare @.i int, @.thiskey nvarchar(131) -- 128+3
> select @.keys = index_col(@.objname, @.indid, 1), @.i = 2
> if (indexkey_property(@.objid, @.indid, 1, 'isdescending') = 1)
> select @.keys = @.keys + '(-)'
> select @.thiskey = index_col(@.objname, @.indid, @.i)
> if ((@.thiskey is not null) and (indexkey_property(@.objid, @.indid, @.i,
>'isdescending') = 1))
> select @.thiskey = @.thiskey + '(-)'
> while (@.thiskey is not null )
> begin
> select @.keys = @.keys + ', ' + @.thiskey, @.i = @.i + 1
> select @.thiskey = index_col(@.objname, @.indid, @.i)
> if ((@.thiskey is not null) and (indexkey_property(@.objid, @.indid,
>@.i, 'isdescending') = 1))
> select @.thiskey = @.thiskey + '(-)'
> end
> select @.groupname = groupname from sysfilegroups where groupid =>@.groupid
> -- INSERT ROW FOR INDEX
> insert into #spindtab values (@.indname, @.status, @.groupname, @.keys)
> -- Next index
> fetch ms_crs_ind into @.indid, @.groupid, @.indname, @.status
> end
> deallocate ms_crs_ind
> -- SET UP SOME CONSTANT VALUES FOR OUTPUT QUERY
> declare @.empty varchar(1) select @.empty = ''
> declare @.des1 varchar(35), -- 35 matches spt_values
> @.des2 varchar(35),
> @.des4 varchar(35),
> @.des32 varchar(35),
> @.des64 varchar(35),
> @.des2048 varchar(35),
> @.des4096 varchar(35),
> @.des8388608 varchar(35),
> @.des16777216 varchar(35)
> select @.des1 = name from master.dbo.spt_values where type = 'I' and
>number = 1
> select @.des2 = name from master.dbo.spt_values where type = 'I' and
>number = 2
> select @.des4 = name from master.dbo.spt_values where type = 'I' and
>number = 4
> select @.des32 = name from master.dbo.spt_values where type = 'I' and
>number = 32
> select @.des64 = name from master.dbo.spt_values where type = 'I' and
>number = 64
> select @.des2048 = name from master.dbo.spt_values where type = 'I' and
>number = 2048
> select @.des4096 = name from master.dbo.spt_values where type = 'I' and
>number = 4096
> select @.des8388608 = name from master.dbo.spt_values where type = 'I'
>and number = 8388608
> select @.des16777216 = name from master.dbo.spt_values where type = 'I'
>and number = 16777216
> -- DISPLAY THE RESULTS
> select
> 'index_name' = index_name,
> 'index_description' = convert(varchar(210), --bits 16 off, 1, 2,
>16777216 on, located on group
> case when (stats & 16)<>0 then 'clustered' else 'nonclustered' end
> + case when (stats & 1)<>0 then ', '+@.des1 else @.empty end
> + case when (stats & 2)<>0 then ', '+@.des2 else @.empty end
> + case when (stats & 4)<>0 then ', '+@.des4 else @.empty end
> + case when (stats & 64)<>0 then ', '+@.des64 else case when (stats
>& 32)<>0 then ', '+@.des32 else @.empty end end
> + case when (stats & 2048)<>0 then ', '+@.des2048 else @.empty end
> + case when (stats & 4096)<>0 then ', '+@.des4096 else @.empty end
> + case when (stats & 8388608)<>0 then ', '+@.des8388608 else @.empty
>end
> + case when (stats & 16777216)<>0 then ', '+@.des16777216 else
>@.empty end
> + ' located on ' + groupname),
> 'index_keys' = index_keys
> from #spindtab
> order by index_name
>
> return (0) -- sp_helpindex
>--
>exec Proc_helpindex_without_pk 'authors'
>try. all the best
>
>

How to get indexes?

I want to get a list of indexes for a certain table. I like the
sp_helpindex [table_name], but it also returns the primary key index.
How can I get what sp_helpindex returns without the primary key index?Hi,
Query either SYSINDEXES table or use sp_help <tablename>
Thanks
Hari
SQL Server MVP
"Frank Rizzo" <none@.none.com> wrote in message
news:upXtVEmvFHA.3756@.tk2msftngp13.phx.gbl...
>I want to get a list of indexes for a certain table. I like the
>sp_helpindex [table_name], but it also returns the primary key index.
How
>can I get what sp_helpindex returns without the primary key index?|||I have created one procedure named "Proc_helpindex_without_pk". 99%
code is copied from sp_helpindex procedure and i added 1% piece of code
to meet your requirments.
Do not update sql server system tables and system procedure.
The Customizied Code is as follows.
create proc Proc_helpindex_without_pk
@.objname nvarchar(776) -- the table to check for indexes
as
-- PRELIM
set nocount on
declare @.objid int, -- the object id of the table
@.indid smallint, -- the index id of an index
@.groupid smallint, -- the filegroup id of an index
@.indname sysname,
@.groupname sysname,
@.status int,
@.keys nvarchar(2126), --Length
(16*max_identifierLength)+(15*2)+(16*3)
@.dbname sysname
-- Check to see that the object names are local to the current
database.
select @.dbname = parsename(@.objname,3)
if @.dbname is not null and @.dbname <> db_name()
begin
raiserror(15250,-1,-1)
return (1)
end
-- Check to see the the table exists and initialize @.objid.
select @.objid = object_id(@.objname)
if @.objid is NULL
begin
select @.dbname=db_name()
raiserror(15009,-1,-1,@.objname,@.dbname)
return (1)
end
-- OPEN CURSOR OVER INDEXES (skip stats: bug shiloh_51196)
declare ms_crs_ind cursor local static for
select indid, groupid, name, status from sysindexes
where id = @.objid and indid > 0 and indid < 255 and (status & 64)=0
and name not in (select constraint_name
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where table_name = object_name(@.objid) and
constraint_type = 'primary key')
order by indid
open ms_crs_ind
fetch ms_crs_ind into @.indid, @.groupid, @.indname, @.status
-- IF NO INDEX, QUIT
if @.@.fetch_status < 0
begin
deallocate ms_crs_ind
raiserror(15472,-1,-1) --'Object does not have any indexes.'
return (0)
end
-- create temp table
create table #spindtab
(
index_name sysname collate database_default NOT NULL,
stats int,
groupname sysname collate database_default NOT NULL,
index_keys nvarchar(2126) collate database_default NOT NULL -- see
@.keys above for length descr
)
-- Now check out each index, figure out its type and keys and
-- save the info in a temporary table that we'll print out at the end.
while @.@.fetch_status >= 0
begin
-- First we'll figure out what the keys are.
declare @.i int, @.thiskey nvarchar(131) -- 128+3
select @.keys = index_col(@.objname, @.indid, 1), @.i = 2
if (indexkey_property(@.objid, @.indid, 1, 'isdescending') = 1)
select @.keys = @.keys + '(-)'
select @.thiskey = index_col(@.objname, @.indid, @.i)
if ((@.thiskey is not null) and (indexkey_property(@.objid, @.indid, @.i,
'isdescending') = 1))
select @.thiskey = @.thiskey + '(-)'
while (@.thiskey is not null )
begin
select @.keys = @.keys + ', ' + @.thiskey, @.i = @.i + 1
select @.thiskey = index_col(@.objname, @.indid, @.i)
if ((@.thiskey is not null) and (indexkey_property(@.objid, @.indid,
@.i, 'isdescending') = 1))
select @.thiskey = @.thiskey + '(-)'
end
select @.groupname = groupname from sysfilegroups where groupid =
@.groupid
-- INSERT ROW FOR INDEX
insert into #spindtab values (@.indname, @.status, @.groupname, @.keys)
-- Next index
fetch ms_crs_ind into @.indid, @.groupid, @.indname, @.status
end
deallocate ms_crs_ind
-- SET UP SOME CONSTANT VALUES FOR OUTPUT QUERY
declare @.empty varchar(1) select @.empty = ''
declare @.des1 varchar(35), -- 35 matches spt_values
@.des2 varchar(35),
@.des4 varchar(35),
@.des32 varchar(35),
@.des64 varchar(35),
@.des2048 varchar(35),
@.des4096 varchar(35),
@.des8388608 varchar(35),
@.des16777216 varchar(35)
select @.des1 = name from master.dbo.spt_values where type = 'I' and
number = 1
select @.des2 = name from master.dbo.spt_values where type = 'I' and
number = 2
select @.des4 = name from master.dbo.spt_values where type = 'I' and
number = 4
select @.des32 = name from master.dbo.spt_values where type = 'I' and
number = 32
select @.des64 = name from master.dbo.spt_values where type = 'I' and
number = 64
select @.des2048 = name from master.dbo.spt_values where type = 'I' and
number = 2048
select @.des4096 = name from master.dbo.spt_values where type = 'I' and
number = 4096
select @.des8388608 = name from master.dbo.spt_values where type = 'I'
and number = 8388608
select @.des16777216 = name from master.dbo.spt_values where type = 'I'
and number = 16777216
-- DISPLAY THE RESULTS
select
'index_name' = index_name,
'index_description' = convert(varchar(210), --bits 16 off, 1, 2,
16777216 on, located on group
case when (stats & 16)<>0 then 'clustered' else 'nonclustered' end
+ case when (stats & 1)<>0 then ', '+@.des1 else @.empty end
+ case when (stats & 2)<>0 then ', '+@.des2 else @.empty end
+ case when (stats & 4)<>0 then ', '+@.des4 else @.empty end
+ case when (stats & 64)<>0 then ', '+@.des64 else case when (stats
& 32)<>0 then ', '+@.des32 else @.empty end end
+ case when (stats & 2048)<>0 then ', '+@.des2048 else @.empty end
+ case when (stats & 4096)<>0 then ', '+@.des4096 else @.empty end
+ case when (stats & 8388608)<>0 then ', '+@.des8388608 else @.empty
end
+ case when (stats & 16777216)<>0 then ', '+@.des16777216 else
@.empty end
+ ' located on ' + groupname),
'index_keys' = index_keys
from #spindtab
order by index_name
return (0) -- sp_helpindex
exec Proc_helpindex_without_pk 'authors'
try. all the best|||Thank you. This is great.
Praveen wrote:

>I have created one procedure named "Proc_helpindex_without_pk". 99%
>code is copied from sp_helpindex procedure and i added 1% piece of code
>to meet your requirments.
>Do not update sql server system tables and system procedure.
>The Customizied Code is as follows.
>create proc Proc_helpindex_without_pk
> @.objname nvarchar(776) -- the table to check for indexes
>as
> -- PRELIM
> set nocount on
> declare @.objid int, -- the object id of the table
> @.indid smallint, -- the index id of an index
> @.groupid smallint, -- the filegroup id of an index
> @.indname sysname,
> @.groupname sysname,
> @.status int,
> @.keys nvarchar(2126), --Length
>(16*max_identifierLength)+(15*2)+(16*3)
> @.dbname sysname
> -- Check to see that the object names are local to the current
>database.
> select @.dbname = parsename(@.objname,3)
> if @.dbname is not null and @.dbname <> db_name()
> begin
> raiserror(15250,-1,-1)
> return (1)
> end
> -- Check to see the the table exists and initialize @.objid.
> select @.objid = object_id(@.objname)
> if @.objid is NULL
> begin
> select @.dbname=db_name()
> raiserror(15009,-1,-1,@.objname,@.dbname)
> return (1)
> end
> -- OPEN CURSOR OVER INDEXES (skip stats: bug shiloh_51196)
> declare ms_crs_ind cursor local static for
> select indid, groupid, name, status from sysindexes
> where id = @.objid and indid > 0 and indid < 255 and (status & 64)=0
> and name not in (select constraint_name
> from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
> where table_name = object_name(@.objid) and
> constraint_type = 'primary key')
> order by indid
> open ms_crs_ind
> fetch ms_crs_ind into @.indid, @.groupid, @.indname, @.status
> -- IF NO INDEX, QUIT
> if @.@.fetch_status < 0
> begin
> deallocate ms_crs_ind
> raiserror(15472,-1,-1) --'Object does not have any indexes.'
> return (0)
> end
> -- create temp table
> create table #spindtab
> (
> index_name sysname collate database_default NOT NULL,
> stats int,
> groupname sysname collate database_default NOT NULL,
> index_keys nvarchar(2126) collate database_default NOT NULL -- see
>@.keys above for length descr
> )
> -- Now check out each index, figure out its type and keys and
> -- save the info in a temporary table that we'll print out at the end.
> while @.@.fetch_status >= 0
> begin
> -- First we'll figure out what the keys are.
> declare @.i int, @.thiskey nvarchar(131) -- 128+3
> select @.keys = index_col(@.objname, @.indid, 1), @.i = 2
> if (indexkey_property(@.objid, @.indid, 1, 'isdescending') = 1)
> select @.keys = @.keys + '(-)'
> select @.thiskey = index_col(@.objname, @.indid, @.i)
> if ((@.thiskey is not null) and (indexkey_property(@.objid, @.indid, @.i,
>'isdescending') = 1))
> select @.thiskey = @.thiskey + '(-)'
> while (@.thiskey is not null )
> begin
> select @.keys = @.keys + ', ' + @.thiskey, @.i = @.i + 1
> select @.thiskey = index_col(@.objname, @.indid, @.i)
> if ((@.thiskey is not null) and (indexkey_property(@.objid, @.indid,
>@.i, 'isdescending') = 1))
> select @.thiskey = @.thiskey + '(-)'
> end
> select @.groupname = groupname from sysfilegroups where groupid =
>@.groupid
> -- INSERT ROW FOR INDEX
> insert into #spindtab values (@.indname, @.status, @.groupname, @.keys)
> -- Next index
> fetch ms_crs_ind into @.indid, @.groupid, @.indname, @.status
> end
> deallocate ms_crs_ind
> -- SET UP SOME CONSTANT VALUES FOR OUTPUT QUERY
> declare @.empty varchar(1) select @.empty = ''
> declare @.des1 varchar(35), -- 35 matches spt_values
> @.des2 varchar(35),
> @.des4 varchar(35),
> @.des32 varchar(35),
> @.des64 varchar(35),
> @.des2048 varchar(35),
> @.des4096 varchar(35),
> @.des8388608 varchar(35),
> @.des16777216 varchar(35)
> select @.des1 = name from master.dbo.spt_values where type = 'I' and
>number = 1
> select @.des2 = name from master.dbo.spt_values where type = 'I' and
>number = 2
> select @.des4 = name from master.dbo.spt_values where type = 'I' and
>number = 4
> select @.des32 = name from master.dbo.spt_values where type = 'I' and
>number = 32
> select @.des64 = name from master.dbo.spt_values where type = 'I' and
>number = 64
> select @.des2048 = name from master.dbo.spt_values where type = 'I' and
>number = 2048
> select @.des4096 = name from master.dbo.spt_values where type = 'I' and
>number = 4096
> select @.des8388608 = name from master.dbo.spt_values where type = 'I'
>and number = 8388608
> select @.des16777216 = name from master.dbo.spt_values where type = 'I'
>and number = 16777216
> -- DISPLAY THE RESULTS
> select
> 'index_name' = index_name,
> 'index_description' = convert(varchar(210), --bits 16 off, 1, 2,
>16777216 on, located on group
> case when (stats & 16)<>0 then 'clustered' else 'nonclustered' end
> + case when (stats & 1)<>0 then ', '+@.des1 else @.empty end
> + case when (stats & 2)<>0 then ', '+@.des2 else @.empty end
> + case when (stats & 4)<>0 then ', '+@.des4 else @.empty end
> + case when (stats & 64)<>0 then ', '+@.des64 else case when (stats
>& 32)<>0 then ', '+@.des32 else @.empty end end
> + case when (stats & 2048)<>0 then ', '+@.des2048 else @.empty end
> + case when (stats & 4096)<>0 then ', '+@.des4096 else @.empty end
> + case when (stats & 8388608)<>0 then ', '+@.des8388608 else @.empty
>end
> + case when (stats & 16777216)<>0 then ', '+@.des16777216 else
>@.empty end
> + ' located on ' + groupname),
> 'index_keys' = index_keys
> from #spindtab
> order by index_name
>
> return (0) -- sp_helpindex
>--
>exec Proc_helpindex_without_pk 'authors'
>try. all the best
>
>

how to get IDENTITY_INSERT Incriment Primary Key ID roll back when the application fails.

My question is how to get IDENTITY_INSERT Incriment Primary Key ID roll back when the application fails.

Using TransactionScope with single connection in DataObject. I am trying to insert row in two dataTable using its own tableAdapter (two tableAdapter).

I have Product table with ProductID primary key with incriment identity. and that ProductID is used to insert row in ProductHistory Table. Lets say Product table has the last ProductID=8 (8 rows) and the next ProductID will be 9.

When I insert row in both table and if the second table insert fails both gets roll back (which is good). but when I insert again another time the Product ID=10 not 9. Is there any way to roll back the ProductID in Product table so when i insert next time it has incriment number instead of gap.

That is the nature of IDENTITY column. The number once assigned to a row is gone whether the transaction succeeds or not. Even if the transaction succeeds, if you delete the row, the number is not re-assigned. Hopefully your application is based only on the PK-FK relationship and not on the serial order of the data.

|||

Thats what I thought but thought there might be a way I guess not, My table relation is based on PK-FK . It looks odd when some one is viewing Product table and has a gap in Product ID in between product (further someone might have question or confuse). I guess I have to manually create Product ID Primary Key data.

Thank for your answer

|||

Just out of curiosity, why is the ProductId important? ProductId should just be a PK to identify the product, it should not matter if there are gaps.

|||

For Developer standpoint it shouldnt matter at all, For other users, they would like to see incriment by 1. The product page displays Product ID, Product Name, Product Insert Date. So if they will see gap in Product ID inbetween they will have question and trust me they dont want that way, I have dealt in similar situation before.

|||

So why is productId even shown? Do users care?

|||

Oh Yes , that is how they identify the product. Product ID is more important then Product Name. Product ID is the key when communicating with anyone and used all over the page. Product come and go. It is very hard to keep up with their name. They find easy with Product ID

|||

rumax96:

Oh Yes , that is how they identify the product. Product ID is more important then Product Name. Product ID is the key when communicating with anyone and used all over the page. Product come and go. It is very hard to keep up with their name. They find easy with Product ID

Then a gap won't matter - unless your users remember that the product they want appeared 4 products further down a page than product 26, and therefore assume they want product 30. I know users can be extremely odd, but that seems to me to be pushing it a bit.

|||

Thanks Mike, I understand , From a developing perspective it doenst make sense wether there is a gap or not in Primary key field. The maing thing is user dont like gap in their ProductID and If that is the way the users wants then We have no choice. Like I said I have deal before in similar situation.

Sunday, February 19, 2012

How to get ID into field upon insert (SCOPE_IDENTITY() ?)

I have two fields:

ID - primary key and identity field (seed 1 increment 1)
GroupID - int

Upon INSERT I want groupID to be the value of ID

The only way I can figure out how to do this (being inexperienced with sql) is to INSERT with GroupID = 0 and then do a SELECT @.iGroupID=SCOPE_IDENTITY() and then UPDATE the record. But even inside a transaction this seems error prone and not the right way. Can anyone tell me the correct way to do this. Thank you in advance.You can try using a trigger.


CREATE TABLE [dbo].[Table1] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[GroupID] [int] NOT NULL ,
[AnotherColumn] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]

CREATE TRIGGER [InsertTrigger] ON [dbo].[Table1]
AFTER INSERT
AS
declare theCursor cursor for SELECT ID FROM inserted
open theCursor
declare @.ThisID int
select @.ThisID = -1
while 1 = 1
begin
fetch next from theCursor into @.ThisID
if @.@.fetch_status <> 0
break
Update Table1
Set GroupID = @.ThisID
WHERE ID=@.ThisID
end
close theCursor
deallocate theCursor

|||I hope you are using SQL Server 2000 ... If that being the case we can use UDFs to accomblish this task ... A typical code snippet for the same looks like below:

CREATE FUNCTION dbo.GetIdentity() RETURNS INT AS
BEGIN
RETURN (IDENT_CURRENT('vin_test'))
END

CREATE TABLE vin_test
(
colAINT IDENTITY(1,1) NOT NULL,
colBINT DEFAULT dbo.GetIdentity(),
colCVARCHAR(10)
)

INSERT INTO vin_test (colC) VALUES ('Test')
SELECT * FROM vin_test|||Yes the ISP is server 2000 and my MSDE seems to support functions but prompts me to select from Inline, Table-values, Scalar-valued, can you please tell me which to select. Also I have about 20 tables I need to do this with. Do I need to write a function for each table?

THANKS!|||Yes, we need to create one for each table. I am sure it is better than creating 10 triggers ... :)

Select the scalar-valued function ...|||My final question:

Is the UDF better/safer/more stable/reliable then what I am doing in the stored procedure where inside a transaction I insert, get the scope_identity and then update the just inserted record. I understand my (hack/kludge?) method may take more server processing but I besides that I am wondering if it is any less reliable then the UDF method. (last question :) again, thanks.|||I can say it with certain that UDFs are quite stable ... There is no second thoughts on that statement. We have used this in our production code and have tested the same with concurrent users ... Works like a gem ... :) ...

Hmm ... the second part of the question has a couple of interesting points to backup:
1. Keep the transaction short. Which means if you have a big routine to do the same it is quite not advisible.
2. CPU cycles are not cheaper and so is memory. If you were to use SPs in such a fashion then we are using both ... :) ... And I dont recommend the same strongly ...

I know this is a delicate topic to answer and can raise a couple of eye-brows who are reading this ... But these are my views on the same. I am open to hear from others if they think otherwise ...|||stored procedures return only integers...UDF can return other datatypes like float...etc
other than that i guess both are similar...in terms of security/performance...etc|||Hmm ... Stored Procedures can also return more than one value using the OUTPUT parameter types ... And I feel that we can do things in UDF that are quite not possible with Stored Procedures ... Read my article on UDF at :http://www.extremeexperts.com/sql/articles/UDFFunctions.aspx ...

And for the present problem description ... I feel UDF is a cleaner and neater way rather than the conventional UDF approach ...