Create Auto ID

Mar 4, 2008

I created a table with a field called myID. I set the data type as "uniqueidentifier", but it won't auto generate. How do I create a field to auto generate a unique number? I'm working with SQL Server 2000 and I'm creating the table from Enterprise Manager.

View 5 Replies


ADVERTISEMENT

How Do I Create An Auto Increment?

Apr 29, 2006

Hi all
 
I just got SQL server 2k5 installed and working....im just trying to figure out how to make an auto incremement column wiht an integer..
 
or has it been replaced with the "unique identifyer"
 
 
Abyss

View 4 Replies View Related

Create Auto Number

Apr 16, 2004

how can i create an auto number field in sql server 2000?

thanks kris

View 1 Replies View Related

Auto Create && Load In SQL Table

Apr 19, 2006

Hi does anyone know how to create a sql table and then import a list by just clicking on a button to call a procedure?CREATE TABLE clients(ClientID VARCHAR(5), ClientName VARCHAR(30), PRIMARY KEY (ClientID));LOAD DATA LOCAL INFILE 'C:/client.csv' INTO TABLE clientsLINES TERMINATED BY '
';

View 1 Replies View Related

Auto Create Statistics / Indexes

Sep 1, 2000

Hi everyone,

I know that statistics called _WA_... are created on tables when auto create statistics is set on a database. Is this an indication that queries against the table would perform better if indexes were created on the columns in question? (The tables I'm interested in optimising are used equally for transactional querying and reporting)

Thanks for any replies!

Les

View 1 Replies View Related

Auto Create History Tables And Triggers

May 30, 2007

For my company, we have made it a standard to create history tables and triggers for the majority of our production tables. I recently grew tired of consistently spending the time needed to create these tables and triggers so I invested some time in creating a script that would auto generate these.

We recently launched a project which required nearly 100 history tables & triggers to be created. This would have normally taken a good day or two to complete. However, with this script it took a near 10 seconds. Here are some details about the script.

The code below creates a stored procedure that receives two input parameters (@TableName & @CreateTrigger) and performs the following actions:

1) Queries system tables to retrieve table schema for @TableName parameter

2) Creates a History table ("History_" + @TableName) to mimic the original table, plus includes additional history columns.

3) If @CreateTrigger = 'Y' then it creates an Update/Delete trigger on the @TableName table, which is used to populate the History table.


/************************************************************************************************************
Created By: Bryan Massey
Created On: 3/11/2007
Comments: Stored proc performs the following actions:
1) Queries system tables to retrieve table schema for @TableName parameter
2) Creates a History table ("History_" + @TableName) to mimic the original table, plus include
additional history columns.
3) If @CreateTrigger = 'Y' then it creates an Update/Delete trigger on the @TableName table,
which is used to populate the History table.
******************************************* MODIFICATIONS **************************************************
MM/DD/YYYY - Modified By - Description of Changes
************************************************************************************************************/
CREATE PROCEDURE DBO.History_Bat_AutoGenerateHistoryTableAndTrigger
@TableName VARCHAR(200),
@CreateTrigger CHAR(1) = 'Y' -- optional parameter; defaults to "Y"
AS


DECLARE @SQLTable VARCHAR(8000), @SQLTrigger VARCHAR(8000), @FieldList VARCHAR(6000), @FirstField VARCHAR(200)
DECLARE @TAB CHAR(1), @CRLF CHAR(1), @SQL VARCHAR(1000), @Date VARCHAR(12)

SET @TAB = CHAR(9)
SET @CRLF = CHAR(13) + CHAR(10)
SET @Date = CONVERT(VARCHAR(12), GETDATE(), 101)
SET @FieldList = ''
SET @SQLTable = ''


DECLARE @TableDescr VARCHAR(500), @FieldName VARCHAR(100), @DataType VARCHAR(50)
DECLARE @FieldLength VARCHAR(10), @Precision VARCHAR(10), @Scale VARCHAR(10), @FieldDescr VARCHAR(500), @AllowNulls VARCHAR(1)

DECLARE CurHistoryTable CURSOR FOR

-- query system tables to get table schema
SELECT CONVERT(VARCHAR(500), SP2.value) AS TableDescription,
CONVERT(VARCHAR(100), SC.Name) AS FieldName, CONVERT(VARCHAR(50), ST.Name) AS DataType,
CONVERT(VARCHAR(10),SC.length) AS FieldLength, CONVERT(VARCHAR(10), SC.XPrec) AS FieldPrecision,
CONVERT(VARCHAR(10), SC.XScale) AS FieldScale,
CASE SC.IsNullable WHEN 1 THEN 'Y' ELSE 'N' END AS AllowNulls
FROM SysObjects SO
INNER JOIN SysColumns SC ON SO.ID = SC.ID
INNER JOIN SysTypes ST ON SC.xtype = ST.xtype
LEFT OUTER JOIN SysProperties SP ON SC.ID = SP.ID AND SC.ColID = SP.SmallID
LEFT OUTER JOIN SysProperties SP2 ON SC.ID = SP2.ID AND SP2.SmallID = 0
WHERE SO.xtype = 'u' AND SO.Name = @TableName
ORDER BY SO.[name], SC.ColOrder

OPEN CurHistoryTable

FETCH NEXT FROM CurHistoryTable INTO @TableDescr, @FieldName, @DataType,
@FieldLength, @Precision, @Scale, @AllowNulls

WHILE @@FETCH_STATUS = 0
BEGIN

-- create list of table columns
IF LEN(@FieldList) = 0
BEGIN
SET @FieldList = @FieldName
SET @FirstField = @FieldName
END
ELSE
BEGIN
SET @FieldList = @FieldList + ', ' + @FieldName
END


IF LEN(@SQLTable) = 0
BEGIN
SET @SQLTable = 'CREATE TABLE [DBO].[History_' + @TableName + '] (' + @CRLF
SET @SQLTable = @SQLTable + @TAB + '[History' + @FieldName + '] [INT] IDENTITY(1,1) NOT NULL,' + @CRLF
END


SET @SQLTable = @SQLTable + @TAB + '[' + @FieldName + '] ' + '[' + @DataType + ']'

IF UPPER(@DataType) IN ('CHAR', 'VARCHAR', 'NCHAR', 'NVARCHAR', 'BINARY')
BEGIN
SET @SQLTable = @SQLTable + '(' + @FieldLength + ')'
END
ELSE IF UPPER(@DataType) IN ('DECIMAL', 'NUMERIC')
BEGIN
SET @SQLTable = @SQLTable + '(' + @Precision + ', ' + @Scale + ')'
END


IF @AllowNulls = 'Y'
BEGIN
SET @SQLTable = @SQLTable + ' NULL'
END
ELSE
BEGIN
SET @SQLTable = @SQLTable + ' NOT NULL'
END

SET @SQLTable = @SQLTable + ',' + @CRLF


FETCH NEXT FROM CurHistoryTable INTO @TableDescr, @FieldName, @DataType,
@FieldLength, @Precision, @Scale, @AllowNulls
END

CLOSE CurHistoryTable
DEALLOCATE CurHistoryTable

-- finish history table script with standard history columns
SET @SQLTable = @SQLTable + @TAB + '[HistoryCreatedOn] [DATETIME] NULL,' + @CRLF
SET @SQLTable = @SQLTable + @TAB + '[HistoryCreatedByUserID] [SMALLINT] NULL,' + @CRLF

SET @SQLTable = @SQLTable + @TAB + '[HistoryCreatedByUserName] [VARCHAR](30) NULL,' + @CRLF
SET @SQLTable = @SQLTable + @TAB + '[HistoryAction] [CHAR](1) NOT NULL' + @CRLF
SET @SQLTable = @SQLTable + ' )'


PRINT @SQLTable

-- execute sql script to create history table
EXEC(@SQLTable)

IF @@ERROR <> 0
BEGIN
PRINT '******************** ERROR CREATING HISTORY TABLE FOR TABLE: ' + @TableName + ' **************************************'
RETURN -1
END


IF @CreateTrigger = 'Y'
BEGIN
-- create history trigger
SET @SQLTrigger = '/************************************************************************************************************' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'Created By: ' + SUSER_SNAME() + @CRLF
SET @SQLTrigger = @SQLTrigger + 'Created On: ' + @Date + @CRLF
SET @SQLTrigger = @SQLTrigger + 'Comments: Auto generated trigger' + @CRLF
SET @SQLTrigger = @SQLTrigger + '***********************************************************************************************/' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'CREATE TRIGGER [Trigger_' + @TableName + '_UpdateDelete] ON DBO.' + @TableName + @CRLF
SET @SQLTrigger = @SQLTrigger + 'FOR UPDATE, DELETE' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'AS' + @CRLF + @CRLF
SET @SQLTrigger = @SQLTrigger + 'DECLARE @Action CHAR(1)' + @CRLF + @CRLF
SET @SQLTrigger = @SQLTrigger + 'IF EXISTS (SELECT ' + @FirstField + ' FROM Inserted)' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'BEGIN' + @CRLF
SET @SQLTrigger = @SQLTrigger + @TAB + 'SET @Action = ''U''' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'END' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'ELSE' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'BEGIN' + @CRLF
SET @SQLTrigger = @SQLTrigger + @TAB + 'SET @Action = ''D''' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'END' + @CRLF + @CRLF
SET @SQLTrigger = @SQLTrigger + 'INSERT INTO History_' + @TableName + @CRLF
SET @SQLTrigger = @SQLTrigger + @TAB + '(' + @FieldList + ', HistoryCreatedOn, HistoryCreatedByUserName, HistoryAction)' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'SELECT ' + @FieldList + ', GETDATE(), SUSER_SNAME(), @Action' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'FROM DELETED'


--PRINT @SQLTrigger

-- execute sql script to create update/delete trigger
EXEC(@SQLTrigger)

IF @@ERROR <> 0
BEGIN
PRINT '******************** ERROR CREATING HISTORY TRIGGER FOR TABLE: ' + @TableName + ' **************************************'
RETURN -1
END

END

View 13 Replies View Related

Auto Create Trigger After Re-initialization Completed

Jan 5, 2006

Hi all,

Is it possible to create a trigger after creation of table during reinitialization?  if so, how can I do that?  Thanks in advance!

View 11 Replies View Related

How To Create A View With An Auto Number Column?

Apr 9, 2008

I have a View created from 2 tables. How do I add an autoindex (0,1,2,3,..) to a new column?

View 8 Replies View Related

Create Procedure Or Trigger To Auto Generate String ID

Feb 20, 2004

Dear everyone,

I would like to create auto-generated "string" ID for any new record inserted in SQL Server 2000.

I have found some SQL Server 2000 book. But it does not cover how to create procedure or trigger to generate auto ID in the string format.

Could anyone know how to do that?? Thanks!!

From,

Roy

View 7 Replies View Related

SQL Server 2014 :: Create Auto Relationship Between Tables

May 12, 2014

I would like to create a auto relationship between tables.

Currently I am using Northwind DB with tables (Orders, OrderDetails, Customers)

Orders ( OrderId, Customerid)
OrderDetails(OrderId)
Customers(CustomerID)

Now, if the user wants to generate a relationship automatically based on SAME FIELD Names.

What is the approach?

View 9 Replies View Related

Creating Trigger To Auto Set Create/modify Dates

Jul 20, 2005

Hi,I'm a newbie to sql server and this may be a really dumb question forsome you. I'm trying to find some examples of sql server triggers thatwill set columns (e.g. the created and modified date columns) if the rowis being inserted and set a column (e.g. just the modified date column)if the row is being updated.I know how to do this in oracle plsql. I would define it as a beforeinsert or update trigger and reference old and new instances of therecord. Does sql server have an equivalent? Is there a better way to dothis in sql server?Thanksericthis is what i do in oracle that i'm trying to do in sqlserver...CREATE OR REPLACE TRIGGER tr_temp_biubefore insert or updateon tempreferencing old as old new as newfor each rowbeginif inserting then:new.created_date := sysdate;end if;:new.modified_date := sysdate;end tr_temp_biu;

View 1 Replies View Related

SQL 2012 :: SSMS Auto-recovery / Auto-save New (unsaved) Queries

Feb 16, 2014

Since upgrading from SQL Server Management Studio 2008 R2, I've noticed that it no longer autosaves queries that have not been manually saved first. If a file has been manually saved the autorecover files end up in the following directory:

%appdata%MicrosoftSQL Server Management Studio11.0AutoRecoverDatSolution1

However, I have ended up in the situation where I have unsaved queries when my computer has crashed and have not been able to recover them.

I have also found references to .sql files stored in temp files in the following directory, but the files here seem to be very haphazardly caught:

%userprofile%AppDataLocalTemp

View 2 Replies View Related

Auto Increment Auto Non-identity Field

Jan 23, 2004

I have an MS SQL Server table with a Job Number field I need this field to start at a certain number then auto increment from there. Is there a way to do this programatically or within MSDE?

Thanks, Justin.

View 3 Replies View Related

Problems On Create Proc Includes Granting Create Table Or View Perissinin SP

Aug 4, 2004

Hi All,

I'm trying to create a proc for granting permission for developer, but I tried many times, still couldn't get successful, someone can help me? The original statement is:

Create PROC dbo.GrantPermission
@user1 varchar(50)

as

Grant create table to @user1
go

Grant create view to @user1
go

Grant create Procedure to @user1
Go



Thanks Guys.

View 14 Replies View Related

Boolean: {[If [table With This Name] Already Exists In [this Sql Database] Then [ Don't Create Another One] Else [create It And Populate It With These Values]}

May 20, 2008

the subject pretty much says it all, I want to be able to do the following in in VB.net code):
 
{[If [table with this name] already exists [in this sql database] then [ don't create another one] else [create it and populate it with these values]}
 
How would I do this?

View 3 Replies View Related

Create Variable To Store Fetched Name To Use Within BEGIN / END Statements To Create A Login

Mar 3, 2014

I created a cursor that moves through a table to retrieve a user's name.When I open this cursor, I create a variable to store the fetched name to use within the BEGIN/END statements to create a login, user, and role.

I'm getting an 'incorrect syntax' error at the variable. For example ..

CREATE LOGIN @NAME WITH PASSWORD 'password'

I've done a bit of research online and found that you cannot use variables to create logins and the like. One person suggested a stored procedure or dynamic SQL, whereas another pointed out that you shouldn't use a stored procedure and dynamic SQL is best.

View 3 Replies View Related

Dynamic Create Table, Create Index Based Upon A Given Database

Jul 20, 2005

Can I dynamically (from a stored procedure) generatea create table script of all tables in a given database (with defaults etc)a create view script of all viewsa create function script of all functionsa create index script of all indexes.(The result will be 4 scripts)Arno de Jong,The Netherlands.

View 1 Replies View Related

Using For Xml Auto

Jul 27, 2004

Does anyone know how to use for xml auto that will format an xml response to show the parent/child relationships? I currently have the parents and children in a temp table and can only get a formatting so that each one is returned at a parent. how can i select the results from the temp table so for xml auto will return the properly formatted xml file?

this is also for the TreeVeiw control.

View 1 Replies View Related

FOR XML AUTO SQL 2K Vs 2K5

Apr 17, 2007

The upgrade adviser for for 2k5 says something about derived tables being handled differently between 2k and 2K5 and it says to query the tables directly but this does not seem to make much sense because I thought FOR XML AUTO just created some generic XML for presentation purposes. These 2 stored procedures that it is complaining about do query the tables directly and they use the FOR XML AUTO to control the output.Does anyone know if I have to worry about this? I am tempted to let this slide and check out this part of the application after the migration happens tomorrow for QA to start testing.Yes I have been googling, checking my books and digging around in BOL. I am not seeing anything.DISREGARD: I found my derived table. It appears to change the output of the XML. Perfect.

View 2 Replies View Related

Can CREATE DATABASE Or CREATE TABLE Be Wrapped In Transactions?

Jul 20, 2005

I have some code that dynamically creates a database (name is @FullName) andthen creates a table within that database. Is it possible to wrap thesethings into a transaction such that if any one of the following fails, thedatabase "creation" is rolledback. Otherwise, I would try deleting on errordetection, but it could get messy.IF @Error = 0BEGINSET @ExecString = 'CREATE DATABASE ' + @FullNameEXEC sp_executesql @ExecStringSET @Error = @@ErrorENDIF @Error = 0BEGINSET @ExecString = 'CREATE TABLE ' + @FullName + '.[dbo].[Image] ( [ID][int] IDENTITY (1, 1) NOT NULL, [Blob] [image] NULL , [DateAdded] [datetime]NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'EXEC sp_executesql @ExecStringSET @Error = @@ErrorENDIF @Error = 0BEGINSET @ExecString = 'ALTER TABLE ' + @FullName + '.[dbo].[Image] WITHNOCHECK ADD CONSTRAINT [PK_Image] PRIMARY KEY CLUSTERED ( [ID] ) ON[PRIMARY]'EXEC sp_executesql @ExecStringSET @Error = @@ErrorEND

View 2 Replies View Related

Create Script To Create/Refresh Identical Database

Mar 26, 2008



I'm new to using SSIS and have been reading and learning slowly how to use it. I'm trying to create an identical copy of our database for reporting. I've used the Import/Export wizard, but have had some issues with foreign keys and with sql_variant columns.

I've tried searching for anything but haven't had any luck as of yet. I guess I don't even know where to start or what to look for.

Any help would be appreciated. Thanks!

View 9 Replies View Related

Auto Increament

Apr 3, 2007

how to auto increament fieldname id which is set as a primary key in sqlserver 2005 inasp.net2.0

View 1 Replies View Related

Format Of For Xml Auto

Apr 11, 2007

I am using sql server 2000 and want to know how to get xml out of the database that looks like this using for xml auto
<Clients> <Client ID="1">  <Employer="Company1" />  <Employer="Company2" />  <Contact type="phone">  <contact type="email" value="test@test.com">  <contact type="phone" value="555-5555"> </Client> <Client ID="2">  <Employer="Company3" />  <Employer="Company4" />  <Contact type="phone">  <contact type="email" value="test@test.com">  <contact type="phone" value="555-5555"> </Client></Clients>
 The problem I am having is that Contact is nested inside employer when I select Employer before Contact and the opposite happens when I select Contact first.  They both join to the Client table so I would assume they both should nest directly under Client.  How do I get different fields to nest directly under the same element like above?

View 2 Replies View Related

Auto SQL Mail

Jun 15, 2007

 Hi,
 
 I have to generate mails automatically based on databse (SQL SERVER) table,In that table  we have expirydate as one column and
                   based on expirydate I have to generate the mails automatically,Please guide me to solve this issue.
                where we have to run the stored procedure.
            Do we have to use jobscheduler?
     please guide me  how to use it
Thanks in avance
regards,
Raja.

View 1 Replies View Related

Auto Counting In SQL

Oct 5, 2007

Hi all,
I would like to have my SQL statement result to return an additional "column", automatically adding an "auto-increasing" number with it.
So if I for example select all Dates older than today's date, I would want something like this:




1
10/12/2006

2
10/18/2006

3
10/20/2006

4
10/22/2006

5
10/30/2006
Keep in mind that it's not my intention to fysically insert the "counting" column into the table, but rather do it "virtually".
Is this possible? And if yes, how ? :)
 
Thanks in advance
Nick

View 6 Replies View Related

Auto Delete?

Oct 9, 2007

is there a way to auto delete all the record that is more than 1 month old compare to the date field in that table.

View 1 Replies View Related

Auto Increment

Mar 24, 2008

 DIAGID is the
field in database which is integer. i want to increment this when page is
loaded.but it is not working..

plz
find mistake ... thanks in advance

 

SqlCommand sqlCmd = new SqlCommand("Select max(DIAGID)  from tblDxactual",
sqlCon);

       
SqlDataReader sqlDr;

       
sqlCon.Open();

       
sqlDr = sqlCmd.ExecuteReader();

       
if (sqlDr.Read())

       
{

           
txtbxDiagID.Text = sqlDr[0].ToString()+ "1"
;    

       
}

       
else

        
txtbxDiagID.Text="1";

       
sqlCon.Close();

View 3 Replies View Related

Auto Email

Sep 9, 2004

Hi All,
I want to write a console application to send email. There is a Date field in the SQL Server and I need to send email 2 weeks before that date.I have no idea how to write a console application and make it work.Does anybody have code for this? If so please post it.
Thanks a lot,
Kumar.

View 2 Replies View Related

MS-SQL: Where's Auto Increment?

Feb 4, 2005

It's been a long time since I've had to check an index for the highest value, then add 1, to create a new unique key. These past few years, it seems this is usually done for you. But now that I'm working with MS-SQL, I don't see it. Is it there? It's doesn't seem to be inherent in the definition.

View 5 Replies View Related

MS SQL 05 Auto Increment

Jan 26, 2006

Hello,
Firstly Hello to everyone I'm new the forum and fairly new to .net
I'm working on web datbase application using visual studios 05 and MS SQL05 I've used 2003 (briefly) before but 2005 is very new to me.
To my problem I download the GUI interface from microsoft so I can now setup a local database and do my own testing.
I have created the table and fields with in it however on a particular table i have made a primary Key and left it as an INT but I would like to set it as auto increment ! I dont know how to select that option as i was used to mysql way of doing things or does this have to be done as a stored procedure ?
Any assistance much appreciated.
 

View 1 Replies View Related

Auto Increament

Apr 1, 2006

hello to all,
In Sql Server 2005, how to create a column that is Auto Increamented ???

View 1 Replies View Related

Help! Log Is Auto Shrinking Itself

Mar 4, 2002

HiRunning SQL 7 sp3 on NT 4

I have a database that has the auto shrink option turned OFF. However, the log file seems to auto shrink after the user
runs bulk insert.

The log file is not setup to auto grow either.Any ideas.

Thanks,
Tariq

View 2 Replies View Related

Auto Increment.... Key&#39;s... Etc..

Apr 4, 2001

I am very new to using SQL server 7. I've always used mysql in the past. I cant figure out howto create a autoincrementing key for my tables... is it possible to do in SQL7?? If so.. how.. i thought you just set the datatype to auto increment etc...

sorry for any oversights...


dave

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved