Showing posts with label create. Show all posts
Showing posts with label create. Show all posts

Friday, March 30, 2012

IF NOT EXISTS

Hello,

I am trying to create a table if one with the same name does not exists. My code is:

Dim connectionStringAsString ="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\PensionDistrict4.mdf;Integrated Security=True;User Instance=True"Dim sqlConnectionAs SqlConnection =New SqlConnection(connectionString)Dim newTableAsString ="CREATE TABLE [" + titleString +"Comments" +"] (ID int NOT NULL PRIMARY KEY IDENTITY, Title varchar(100) NOT NULL, Name varchar(100) NOT NULL, Comment varchar(MAX) NOT NULL, Date datetime NOT NULL)"

sqlConnection.Open()

Dim sqlExistsAsString ="IF EXISTS (SELECT * FROM PensionDistrict4 WHERE name = '" + titleString +"Comments" +"')"Dim sqlCommandAsNew SqlCommand(newTable, sqlConnection)If sqlExists =TrueThen

sqlCommand.Cancel()

Else

sqlCommand.ExecuteNonQuery()

sqlConnection.Close()

EndIf

I keep getting a "Input String was incorrect format" for sqlExists? I am new to Transact-SQL statements, any help would be appreciated.

Thanks Matt

your sql Exists is just a string. so your code ofIf sqlExists =TrueThen doesnt make any sense. You need to execute it to find out if a table with the name exists. Alternatively its better to query sysobjects to find out if the table exists.

SELECT * FROM ssyobjects WHERE [Name] = '...' AND xtype = 'u'.

I'd recommend using a stored proc for this, so you can query the sysobjects to see if the table already exists and if it does not then create it else either drop and recreate ot exit appropriately.

If I had any hair left I'd pull it out. How do I create a SSIS Package which creates a table th

Hello everyone,

I'm not at all comfortable with SSIS so please forgive me if I overload you all with information here:

I need to create a data table using SSIS which does not delete the previous days data. So far all the data tables we use to write reports in Visual Studio are constructed in SSIS as follows.

1 - Excecute SQL Task - DELETE FROM STOCK
2 - Data Flow Task
3 - Data Reader Source - SELECT * FROM ODBCDATASOURCE
4 - OLE DB Destination (Creates table STOCK)

The data tables which are created this way are stored in a data warehouse and scheduled to refresh once a day, which means that any data from yesterday is lost when the updates run. So, I tried to create a table which never has its previous days' data deleted by using just the last three steps above - and it worked great in Visual Studio, no problem at all. However, when I added this SSIS Package to the Update Job in SQL Server Management Studio, the job totally rejected the packed with the message: "The command line parameters are invalid. The step failed".

I thought I could work around this problem by asking the job step to excecute a simple SQL query to insert the data from table1 into table2 (and would thus negate the need for a SSIS Packege at all), but it threw me a curve ball with some message about not being able to use proxy accounts to run T-SQL Scripts.

If anyone knows how to create a SSIS package in which the data never expires please could you impart some wisdom my way. I only need to do this once for a specific report.

Please, when answering, bear in mind that I'm a simple fellow with little understanding of the inner workings of SQL Server and its various components, so please use short sentences and simple words.

Thanks in advance,

Chris

Strange. Looks like a problem in SQL Agent.

I suggest you first attempt to execute the package using dtexec. Once you have got that working we can talk about transferring the command-line to SQL Agent.

To make it easy to build the command-line for use with dtexec, Microsoft provide a tool called dtexecui that builds the command-line for you. Just type "dtexecui" at the command prompt.

If none of that makes sense, just holler.

-Jamie

|||

Jamie,

First of all, many thanks for your reply, your help is much appreciated.

I did what you suggested and tried to run the package via dtexec, but after a couple of validation phases it gave this error message: Error: The product level is insufficient for component "DataReader Source" (1).

Any suggestions on what I've not done correctly would be appreciated.

Many thanks,

Chris

|||

A common issue, normaly caused by not having a full SSIS installation on that machine.

Michael Entin's WebLog : Why do I get "product level is insufficient..." error when I run my SSIS package?
(http://blogs.msdn.com/michen/archive/2006/11/11/ssis-product-level-is-insufficient.aspx)

Product level is insufficient
(http://msdn2.microsoft.com/en-us/library/aa337371.aspx)

|||

Darren,

Thank you, I have just run the package via remote desktop to the server and it ran successfully first time.

How do I now get the package to run as part of the SQL Server Agent Job? The package step still fails whether initiated or scheduled and whether run locally or from the server.

Thanks,

Chris

|||

C.P.Hardcastle wrote:

Darren,

Thank you, I have just run the package via remote desktop to the server and it ran successfully first time.

How did you execute it? From BIDS or using dtexec?

C.P.Hardcastle wrote:

How do I now get the package to run as part of the SQL Server Agent Job? The package step still fails whether initiated or scheduled and whether run locally or from the server.

Thanks,

Chris

What is the error message?

-Jamie

|||

Jamie,

I can execute the package successfully from either BIDS (VS2005) on my local machine, or from dtexec if I remote desktop to the server and run it from there.

The package consistently fails when run in SQL Server Agent within SQL Server Management Studio - I can be running SSMS locally or on the server and it makes no difference. When I open the job and view the job history the step that runs this package fails with the error: The command line parameters are invalid. The step failed.

All other steps (three other steps) in the job complete successfully, this is the only step that fails (I've swapped the order in which they run and this one always fails while the other three always complete successfully). I have checked and double checked that the job and steps are set up properly and I even isolated this one package into a seperate Job all of its own and it still fails.

I have even gone as far as to delete the package, recreate the package, save copy to the server etc and I always get the same results when I try to run the SS Agent Job.

Any suggestions are very welcome.

Many thanks for your help so far and for your time and energy with this,

Chris

|||

C.P.Hardcastle wrote:

Jamie,

I can execute the package successfully from either BIDS (VS2005) on my local machine, or from dtexec if I remote desktop to the server and run it from there.

The package consistently fails when run in SQL Server Agent within SQL Server Management Studio - I can be running SSMS locally or on the server and it makes no difference. When I open the job and view the job history the step that runs this package fails with the error: The command line parameters are invalid. The step failed.

All other steps (three other steps) in the job complete successfully, this is the only step that fails (I've swapped the order in which they run and this one always fails while the other three always complete successfully). I have checked and double checked that the job and steps are set up properly and I even isolated this one package into a seperate Job all of its own and it still fails.

I have even gone as far as to delete the package, recreate the package, save copy to the server etc and I always get the same results when I try to run the SS Agent Job.

Any suggestions are very welcome.

Many thanks for your help so far and for your time and energy with this,

Chris

Did you change to use the command-line subsystem as per my earlier suggestion? If so, what is the command-line that you are using?

-Jamie

|||

Jamie,

I must apologise, I really appreciate your help and I really don't want to exhaust your patience, but please understand your dealing with ineptitude of idiotic proportions here.

Here's exactly what I did. At the command prompt I typed "dtexecui" as you suggested. This opened a new window called Execute Package Utility. I then entered the relevant information about which package to execute and it then went through a few validation phases and the Package execution Process Window returned a message that "component "OLE DB Destination" (13)" wrote 248 rows.

I once again apologise, but I'm not exactly sure what you mean by what is the command-line I'm using, but the only thing that I think you mean is this:

/DTS "/MSDB/C002_UNIDATA_STOCKPE_RD" /SERVER LYSRVBI /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING EW

This command line differs slightly to the one used by the Agent Job Step, which is:

/DTS "/MSDB/C002_UNIDATA_STOCKPE_RD" /SERVER LYSRVBI /MAXCONCURRENT " -1 " /CHECKPOINTING OFF

..so I copied the command line from the dtexec utility into the step for this package but it still fails.

I hope I have given you the right information here.

Thanks again,

Chris

|||

C.P.Hardcastle wrote:

Jamie,

I must apologise, I really appreciate your help and I really don't want to exhaust your patience, but please understand your dealing with ineptitude of idiotic proportions here.

Here's exactly what I did. At the command prompt I typed "dtexecui" as you suggested. This opened a new window called Execute Package Utility. I then entered the relevant information about which package to execute and it then went through a few validation phases and the Package execution Process Window returned a message that "component "OLE DB Destination" (13)" wrote 248 rows.

I once again apologise, but I'm not exactly sure what you mean by what is the command-line I'm using, but the only thing that I think you mean is this:

/DTS "/MSDB/C002_UNIDATA_STOCKPE_RD" /SERVER LYSRVBI /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING EW

This command line differs slightly to the one used by the Agent Job Step, which is:

/DTS "/MSDB/C002_UNIDATA_STOCKPE_RD" /SERVER LYSRVBI /MAXCONCURRENT " -1 " /CHECKPOINTING OFF

..so I copied the command line from the dtexec utility into the step for this package but it still fails.

I hope I have given you the right information here.

Thanks again,

Chris

Chris,

I think you do yourself a disservice. You've done (almost) exactly what I suggested so you're not as inept as you may think.

What you need to do first is take the command line from dtexecui, and run it using dtexec. See if that works or fails.

i.e., Something like this:

dtexec /DTS "/MSDB/C002_UNIDATA_STOCKPE_RD" /SERVER LYSRVBI /MAXCONCURRENT " -1 " /CHECKPOINTING OFF

-Jamie

|||Jamie,

Thanks once again for your reply and for your encouraging comments.

I'm out of the office now until Monday so I won't have the chance to try your suggestion for a few days.

I will let you know how it goes as soon as I can.

Thanks again, your help is very much appreciated.

All the best,

Chris|||Jamie,

I couldn't resist a VPN to the server from home to try your suggestion.

Unfortunately, the job still fails.

Chris|||

C.P.Hardcastle wrote:

Jamie,

I couldn't resist a VPN to the server from home to try your suggestion.

Unfortunately, the job still fails.

Chris

When using dtexec or from SQL Agent? it does not make sense that it would work from dtexecui and not dtexec.

Please provide more info.

-Jamie

|||

Jamie Thomson wrote:

When using dtexec or from SQL Agent? it does not make sense that it would work from dtexecui and not dtexec.

Please provide more info.

-Jamie

Especially since dtexecui is a wrapper to dtexec.|||Jamie,

I'll give you as much information as I can.

As I said before, all our SSIS packages are createde in the same way with the same four steps: Execute SQL Task > Data Flow Task > Data Reader Source > OLE DB Destination.

With the exception that this problem package omits the Execute SQL Task stage it is identically set up to all our other packages, which work flawlessly.

After I created the package in Visual Studio I executed the package and everything turned green and all messages told me that the execution was a success. Sure enough if I viewed the table from server explorer all the data I expected to see was present.

Next I changed the protection level to Server Storage and saved a copy of the package to the server using the following:

Package Location: SSIS Package Store
Server: LYSRVBI
Windows Authentication
Package Path: /MSDB/C002_UNIDATA_STOCKPE_RD
Protectin Level: Rely on server storage and rules for access control

Next I created a new SSA job in SQL Server Management Studio and created a new step using the following:

Job Type: SSIS Package
Package Source: SSIS Package Store
Server: LYSRVBI
Use Windows Authentication
Package Path /MSDB/C002_UNIDATA_STOCKPE_RD

In the advanced section I made sure that close reporting success and close reporting failure were appropriately set depending on the execution outcome.

When I tried to run this job it consistently failed so I then followed your advice and ran the package via dtexecui after connecting to the server via remote desktop - and it worked. I copied the command line from dtexecui and edited the command line within the job to the same adding "dtexec" to the front of the command as you suggested- I left evertything else in the job/step exactly as above. When I started the job it immediately failed.

I don't think I've left anything out and I'm really baffled why it won't run as it's identical to countless other packages we run everyday with the only exception being that it omits the Execute SQL Task step and the "DELETE FROM <TABLENAME>" string within that task.

Let me know if I've made any fundamental errors please?

Thanks,

Chris

IF funcionality in SQL server views

Hi,
I am working with several tables and views. My goal is to create a view
with critical reporting data from these tables and views. I have
managed to get the majority of data but am having difficultly with the
final step.
For a record in the master dataview, add additional record information
by appending data from another view based on the first 2 letters of the
document number and the document number i.e
Document number
SC11111
DN22222
SI33333
For SC11111 look up data in Sales Credit table/view for doument SC11111
and append to that line
For DN22222 look up data in Delivery Note table/view for document
DN22222and append to that line
For SI33333 look up data in Sales Invoice table/view for document
SI33333 and append to that line
Any help appreciated.
Thank you in advance,
RajCan I just clarify what you're trying to do...
as I understand it, you want to select from different tables/views
depending on what the data is.
if so, could you left join on all 3 tables, then using join filters and
using isnull() in your select you could just get the data from the
relevant table.
Otherwise, could you explain a bit further what the problem is.
Cheers
Will|||If you want to conditional view, you can make a view using Multi-statement
Function.
"the_raj"ë'ì?´ ì'ì?±í' ë?´ì?©:
> Hi,
> I am working with several tables and views. My goal is to create a view
> with critical reporting data from these tables and views. I have
> managed to get the majority of data but am having difficultly with the
> final step.
> For a record in the master dataview, add additional record information
> by appending data from another view based on the first 2 letters of the
> document number and the document number i.e
> Document number
> SC11111
> DN22222
> SI33333
> For SC11111 look up data in Sales Credit table/view for doument SC11111
> and append to that line
> For DN22222 look up data in Delivery Note table/view for document
> DN22222and append to that line
> For SI33333 look up data in Sales Invoice table/view for document
> SI33333 and append to that line
> Any help appreciated.
> Thank you in advance,
> Raj
>|||Since you haven't provided the ddls I will try to explain it with a snippet.
CREATE VIEW MASTER_VIEW
AS
SELECT A.*, B.*
FROM MASTER_DATA A, SALES_CREDIT B
WHERE SUBSTRING(A. DOCUMENT_NUMBER,1,2) = 'SC'
AND <JOIN CODITIONS>
UNION ALL
SELECT A.*, C.*
FROM MASTER_DATA A, DELIVERY_NOTE C
WHERE SUBSTRING(A. DOCUMENT_NUMBER,1,2) = 'DN'
AND <JOIN CODITIONS>
UNION ALL
SELECT A.*, B.*
FROM MASTER_DATA A, SALES_INVOICE C
WHERE SUBSTRING(A. DOCUMENT_NUMBER,1,2) = 'SI'
AND <JOIN CODITIONS>
--Note: do not use select *
-- and I assume the 3 selects that are unioned will be having the same schema

IF funcionality in SQL server views

Hi,
I am working with several tables and views. My goal is to create a view
with critical reporting data from these tables and views. I have
managed to get the majority of data but am having difficultly with the
final step.
For a record in the master dataview, add additional record information
by appending data from another view based on the first 2 letters of the
document number and the document number i.e
Document number
SC11111
DN22222
SI33333
For SC11111 look up data in Sales Credit table/view for doument SC11111
and append to that line
For DN22222 look up data in Delivery Note table/view for document
DN22222and append to that line
For SI33333 look up data in Sales Invoice table/view for document
SI33333 and append to that line
Any help appreciated.
Thank you in advance,
Raj
Can I just clarify what you're trying to do...
as I understand it, you want to select from different tables/views
depending on what the data is.
if so, could you left join on all 3 tables, then using join filters and
using isnull() in your select you could just get the data from the
relevant table.
Otherwise, could you explain a bit further what the problem is.
Cheers
Will
|||If you want to conditional view, you can make a view using Multi-statement
Function.
"the_raj"?? ??? ??:

> Hi,
> I am working with several tables and views. My goal is to create a view
> with critical reporting data from these tables and views. I have
> managed to get the majority of data but am having difficultly with the
> final step.
> For a record in the master dataview, add additional record information
> by appending data from another view based on the first 2 letters of the
> document number and the document number i.e
> Document number
> SC11111
> DN22222
> SI33333
> For SC11111 look up data in Sales Credit table/view for doument SC11111
> and append to that line
> For DN22222 look up data in Delivery Note table/view for document
> DN22222and append to that line
> For SI33333 look up data in Sales Invoice table/view for document
> SI33333 and append to that line
> Any help appreciated.
> Thank you in advance,
> Raj
>
|||Since you haven't provided the ddls I will try to explain it with a snippet.
CREATE VIEW MASTER_VIEW
AS
SELECT A.*, B.*
FROM MASTER_DATA A, SALES_CREDIT B
WHERE SUBSTRING(A. DOCUMENT_NUMBER,1,2) = 'SC'
AND <JOIN CODITIONS>
UNION ALL
SELECT A.*, C.*
FROM MASTER_DATA A, DELIVERY_NOTE C
WHERE SUBSTRING(A. DOCUMENT_NUMBER,1,2) = 'DN'
AND <JOIN CODITIONS>
UNION ALL
SELECT A.*, B.*
FROM MASTER_DATA A, SALES_INVOICE C
WHERE SUBSTRING(A. DOCUMENT_NUMBER,1,2) = 'SI'
AND <JOIN CODITIONS>
--Note: do not use select *
-- and I assume the 3 selects that are unioned will be having the same schema
sql

IF funcionality in SQL server views

Hi,
I am working with several tables and views. My goal is to create a view
with critical reporting data from these tables and views. I have
managed to get the majority of data but am having difficultly with the
final step.
For a record in the master dataview, add additional record information
by appending data from another view based on the first 2 letters of the
document number and the document number i.e
Document number
SC11111
DN22222
SI33333
For SC11111 look up data in Sales Credit table/view for doument SC11111
and append to that line
For DN22222 look up data in Delivery Note table/view for document
DN22222and append to that line
For SI33333 look up data in Sales Invoice table/view for document
SI33333 and append to that line
Any help appreciated.
Thank you in advance,
RajCan I just clarify what you're trying to do...
as I understand it, you want to select from different tables/views
depending on what the data is.
if so, could you left join on all 3 tables, then using join filters and
using isnull() in your select you could just get the data from the
relevant table.
Otherwise, could you explain a bit further what the problem is.
Cheers
Will|||If you want to conditional view, you can make a view using Multi-statement
Function.
"the_raj"?? ??? ??:

> Hi,
> I am working with several tables and views. My goal is to create a view
> with critical reporting data from these tables and views. I have
> managed to get the majority of data but am having difficultly with the
> final step.
> For a record in the master dataview, add additional record information
> by appending data from another view based on the first 2 letters of the
> document number and the document number i.e
> Document number
> SC11111
> DN22222
> SI33333
> For SC11111 look up data in Sales Credit table/view for doument SC11111
> and append to that line
> For DN22222 look up data in Delivery Note table/view for document
> DN22222and append to that line
> For SI33333 look up data in Sales Invoice table/view for document
> SI33333 and append to that line
> Any help appreciated.
> Thank you in advance,
> Raj
>|||Since you haven't provided the ddls I will try to explain it with a snippet.
CREATE VIEW MASTER_VIEW
AS
SELECT A.*, B.*
FROM MASTER_DATA A, SALES_CREDIT B
WHERE SUBSTRING(A. DOCUMENT_NUMBER,1,2) = 'SC'
AND <JOIN CODITIONS>
UNION ALL
SELECT A.*, C.*
FROM MASTER_DATA A, DELIVERY_NOTE C
WHERE SUBSTRING(A. DOCUMENT_NUMBER,1,2) = 'DN'
AND <JOIN CODITIONS>
UNION ALL
SELECT A.*, B.*
FROM MASTER_DATA A, SALES_INVOICE C
WHERE SUBSTRING(A. DOCUMENT_NUMBER,1,2) = 'SI'
AND <JOIN CODITIONS>
--Note: do not use select *
-- and I assume the 3 selects that are unioned will be having the same schem
a

IF funcionality in SQL server views

Hi,
I am working with several tables and views. My goal is to create a view
with critical reporting data from these tables and views. I have
managed to get the majority of data but am having difficultly with the
final step.
For a record in the master dataview, add additional record information
by appending data from another view based on the first 2 letters of the
document number and the document number i.e
Document number
SC11111
DN22222
SI33333
For SC11111 look up data in Sales Credit table/view for doument SC11111
and append to that line
For DN22222 look up data in Delivery Note table/view for document
DN22222and append to that line
For SI33333 look up data in Sales Invoice table/view for document
SI33333 and append to that line
Any help appreciated.
Thank you in advance,
RajCan I just clarify what you're trying to do...
as I understand it, you want to select from different tables/views
depending on what the data is.
if so, could you left join on all 3 tables, then using join filters and
using isnull() in your select you could just get the data from the
relevant table.
Otherwise, could you explain a bit further what the problem is.
Cheers
Will|||If you want to conditional view, you can make a view using Multi-statement
Function.
"the_raj"?? ??? ??:

> Hi,
> I am working with several tables and views. My goal is to create a view
> with critical reporting data from these tables and views. I have
> managed to get the majority of data but am having difficultly with the
> final step.
> For a record in the master dataview, add additional record information
> by appending data from another view based on the first 2 letters of the
> document number and the document number i.e
> Document number
> SC11111
> DN22222
> SI33333
> For SC11111 look up data in Sales Credit table/view for doument SC11111
> and append to that line
> For DN22222 look up data in Delivery Note table/view for document
> DN22222and append to that line
> For SI33333 look up data in Sales Invoice table/view for document
> SI33333 and append to that line
> Any help appreciated.
> Thank you in advance,
> Raj
>|||Since you haven't provided the ddls I will try to explain it with a snippet.
CREATE VIEW MASTER_VIEW
AS
SELECT A.*, B.*
FROM MASTER_DATA A, SALES_CREDIT B
WHERE SUBSTRING(A. DOCUMENT_NUMBER,1,2) = 'SC'
AND <JOIN CODITIONS>
UNION ALL
SELECT A.*, C.*
FROM MASTER_DATA A, DELIVERY_NOTE C
WHERE SUBSTRING(A. DOCUMENT_NUMBER,1,2) = 'DN'
AND <JOIN CODITIONS>
UNION ALL
SELECT A.*, B.*
FROM MASTER_DATA A, SALES_INVOICE C
WHERE SUBSTRING(A. DOCUMENT_NUMBER,1,2) = 'SI'
AND <JOIN CODITIONS>
--Note: do not use select *
-- and I assume the 3 selects that are unioned will be having the same schem
a

IF funcionality in SQL server views

Hi,

I am working with several tables and views. My goal is to create a view
with critical reporting data from these tables and views. I have
managed to get the majority of data but am having difficultly with the
final step.

For a record in the master dataview, add additional record information
by appending data from another view based on the first 2 letters of the
document number and the document number i.e

Document number
SC11111
DN22222
SI33333

For SC11111 look up data in Sales Credit table/view for doument SC11111
and append to that line
For DN22222 look up data in Delivery Note table/view for document
DN22222and append to that line
For SI33333 look up data in Sales Invoice table/view for document
SI33333 and append to that line

Any help appreciated.

Thank you in advance,

RajCan I just clarify what you're trying to do...

as I understand it, you want to select from different tables/views
depending on what the data is.

if so, could you left join on all 3 tables, then using join filters and
using isnull() in your select you could just get the data from the
relevant table.

Otherwise, could you explain a bit further what the problem is.

Cheers
Will

If exists update, if it doesn't exist create

What I am looking for is a table that has two columns we'll say FName and Timestamp. What I want to do is to see if that name exists in my records. If it does I want to update it with a new timestamp. If it does not I want to create a new record in my table. This is going to be a check from vb 6.0 that is running continuously, so it will run the stored procedure to look for Redundancy in the FName column, if it finds it I want it to update the timestamp in that record to show the most up to date time.

Thank you in advance.First, check if the record exists, if not then add it to the table :

IF NOT EXISTS (SELECT (1) FROM 'table' WHERE FNAME = 'name')
Insert new record into table

Now update the table

UPDATE 'table'
SET TimeStamp = CURRENT_TIMESTAMP
WHERE fname = 'name'|||

Quote:

Originally Posted by SkinHead

First, check if the record exists, if not then add it to the table :

IF NOT EXISTS (SELECT (1) FROM 'table' WHERE FNAME = 'name')
Insert new record into table

Now update the table

UPDATE 'table'
SET TimeStamp = CURRENT_TIMESTAMP
WHERE fname = 'name'


Thanks for the reply. I guess I wrote my question wrong. I need this stored procedure to search a table for any names that it finds to be the same, not just a specific one, and replace the timestamp with a new timestamp.|||

Quote:

Originally Posted by JReneau35

Thanks for the reply. I guess I wrote my question wrong. I need this stored procedure to search a table for any names that it finds to be the same, not just a specific one, and replace the timestamp with a new timestamp.


You do have a specific name your searching for though right? This method will update all of the records matching your input parameter.

You come in with a name and you want it to search for that name in a table. If it doesnt find it, you want one new record created with a timestamp. If it does find it, no matter how many times it finds it, you want all of them updated.

Am I understanding you right?

Wednesday, March 28, 2012

If Exists Schema Fails

Could someone explain why

IF SCHEMA_ID('TestSchema') is nul CREATE SCHEMA TestSchema

Fails with Incorrect syntax near the keyword 'SCHEMA'.

Where as running the following statements

CREATE SCHEMA TestSchema

and

IF SCHEMA_ID('TestSchema') is null SELECT 1

succeeds without a problem.

Thanks

_GJK

Ok. I found the solution from

http://groups.google.com/group/microsoft.public.sqlserver.newusers/browse_thread/thread/69a4e9c45d045120/77c693f5043fbddc?lnk=st&q=schema_id&rnum=1#77c693f5043fbddc

|||

Actually the real root of your problem is that CREATE SCHEMA must be the first statement in a batch. Using dynamic SQL (as suggested in the link above) is a workaround as the dynamic statement itself is considered a new batch.

-Raul Garcia

SDE/T

SQL Server Engine

If exists for temp table

What is the syntax to drop a temporary table if exists ? I want to drop a
temp table ##temptable if exist before I try to create it.
Thanks.create table ##temptable (id int)
IF OBJECT_ID('tempdb..##temptable') IS NOT NULL
BEGIN
PRINT '##temptable exists!'
END
ELSE
BEGIN
PRINT '##temptable does not exist!'
END
Denis the SQL Menace
http://sqlservercode.blogspot.com/
DXC wrote:
> What is the syntax to drop a temporary table if exists ? I want to drop a
> temp table ##temptable if exist before I try to create it.
> Thanks.|||I forgot the drop part, here is the whole thing
CREATE TABLE ##temptable (id int)
GO
IF OBJECT_ID('tempdb..##temptable') IS NOT NULL
BEGIN
PRINT '##temptable exists!'
DROP TABLE ##temptable
END
ELSE
BEGIN
PRINT '##temptable does not exist!'
END
GO
CREATE TABLE ##temptable (id int)
GO
Denis the SQL Menace
http://sqlservercode.blogspot.com/
DXC wrote:
> What is the syntax to drop a temporary table if exists ? I want to drop a
> temp table ##temptable if exist before I try to create it.
> Thanks.|||Thanks............
"SQL" wrote:
> I forgot the drop part, here is the whole thing
> CREATE TABLE ##temptable (id int)
> GO
> IF OBJECT_ID('tempdb..##temptable') IS NOT NULL
> BEGIN
> PRINT '##temptable exists!'
> DROP TABLE ##temptable
> END
> ELSE
> BEGIN
> PRINT '##temptable does not exist!'
> END
> GO
> CREATE TABLE ##temptable (id int)
> GO
> Denis the SQL Menace
> http://sqlservercode.blogspot.com/
>
> DXC wrote:
> > What is the syntax to drop a temporary table if exists ? I want to drop a
> > temp table ##temptable if exist before I try to create it.
> >
> > Thanks.
>

If exists for temp table

What is the syntax to drop a temporary table if exists ? I want to drop a
temp table ##temptable if exist before I try to create it.
Thanks.create table ##temptable (id int)
IF OBJECT_ID('tempdb..##temptable') IS NOT NULL
BEGIN
PRINT '##temptable exists!'
END
ELSE
BEGIN
PRINT '##temptable does not exist!'
END
Denis the SQL Menace
http://sqlservercode.blogspot.com/
DXC wrote:
> What is the syntax to drop a temporary table if exists ? I want to drop a
> temp table ##temptable if exist before I try to create it.
> Thanks.|||I forgot the drop part, here is the whole thing
CREATE TABLE ##temptable (id int)
GO
IF OBJECT_ID('tempdb..##temptable') IS NOT NULL
BEGIN
PRINT '##temptable exists!'
DROP TABLE ##temptable
END
ELSE
BEGIN
PRINT '##temptable does not exist!'
END
GO
CREATE TABLE ##temptable (id int)
GO
Denis the SQL Menace
http://sqlservercode.blogspot.com/
DXC wrote:
> What is the syntax to drop a temporary table if exists ? I want to drop a
> temp table ##temptable if exist before I try to create it.
> Thanks.|||Thanks............
"SQL" wrote:

> I forgot the drop part, here is the whole thing
> CREATE TABLE ##temptable (id int)
> GO
> IF OBJECT_ID('tempdb..##temptable') IS NOT NULL
> BEGIN
> PRINT '##temptable exists!'
> DROP TABLE ##temptable
> END
> ELSE
> BEGIN
> PRINT '##temptable does not exist!'
> END
> GO
> CREATE TABLE ##temptable (id int)
> GO
> Denis the SQL Menace
> http://sqlservercode.blogspot.com/
>
> DXC wrote:
>

if else with WHERE

Hi,
I'm trying to create a store proc and use a WHERE clause only if a certain
condition is met. When I use the WHERE after an if condition, the sql
enterprise tool tells me
it's invalid. "Invalid syntax near WHERE clause"
Here is my proc:
CREATE PROCEDURE [dbo].GetContractorsList
@.characterFilter char(1)
AS
SELECT
[ContractorCode],
[ContractorName],
FROM
[dbo].[Contractors]
if @.characterFilter !='*'
begin
WHERE ContractorName LIKE @.characterFilter + '%'
end
Any ideas on how to do this?
Thanks,
OpaOpa wrote:
> Hi,
> I'm trying to create a store proc and use a WHERE clause only if a
> certain condition is met. When I use the WHERE after an if
> condition, the sql enterprise tool tells me
> it's invalid. "Invalid syntax near WHERE clause"
>
http://www.sommarskog.se/dyn-search.html
Microsoft MVP - ASP/ASP.NET
Please reply to the newsgroup. This email account is my spam trap so I
don't check it very often. If you must reply off-line, then remove the
"NO SPAM"|||Thanks for your reply Bob.
The article you posted is quite lengthy and refers to Dynamic SQL.
Can I do this without it?
"Bob Barrows [MVP]" wrote:

> Opa wrote:
> http://www.sommarskog.se/dyn-search.html
> --
> Microsoft MVP - ASP/ASP.NET
> Please reply to the newsgroup. This email account is my spam trap so I
> don't check it very often. If you must reply off-line, then remove the
> "NO SPAM"
>
>|||Yes, one of the methods described in the article should suit your purpose:
WHERE (@.characterFilter != '*' OR ContractorName LIKE @.characterFilter +
'%')
I suggest you read the entire article. It is quite informative.
Opa wrote:
> Thanks for your reply Bob.
> The article you posted is quite lengthy and refers to Dynamic SQL.
> Can I do this without it?
>
> "Bob Barrows [MVP]" wrote:
>
Microsoft MVP - ASP/ASP.NET
Please reply to the newsgroup. This email account is my spam trap so I
don't check it very often. If you must reply off-line, then remove the
"NO SPAM"

IF ELSE not compiling

I can't seem to figure out why this SP would not compile. Your assistance i
s
much appreciated.
CREATE PROCEDURE sp_getPubId
@.name varchar, @.pubCode varchar, @.pubId smallint Output
AS
DECLARE maxPubId smallint
if (exists
(select publication_id from publication where code =@.pubCode))
begin
@.maxPubId=(select publication_id from publication where code =@.pubCode)
@.pubId=@.maxPubId
end
else begin
@.maxPubId=select max(publication_id) from publication
insert into publication(publication_id, name, code, creation_date,
update_date, last_user_id, status, transmit_app, application_type,
flags)values(@.maxPubId, @.name, @.pubCode, getDate(), getDate(), 13, 1, 1, 1,0
)
@.pubId=@.maxPubId+1
end
return
--
bicHi
Just try it this way:
SET @.maxPubId=(select publication_id from publication where code =@.pubCode)
SET @.pubId=@.maxPubId
.
.
.
best Regards,
Chandra
http://chanduas.blogspot.com/
http://groups.msn.com/SQLResource/
---
"bic" wrote:

> I can't seem to figure out why this SP would not compile. Your assistance
is
> much appreciated.
> CREATE PROCEDURE sp_getPubId
> @.name varchar, @.pubCode varchar, @.pubId smallint Output
> AS
> DECLARE maxPubId smallint
> if (exists
> (select publication_id from publication where code =@.pubCode))
> begin
> @.maxPubId=(select publication_id from publication where code =@.pubCode)
> @.pubId=@.maxPubId
> end
> else begin
> @.maxPubId=select max(publication_id) from publication
> insert into publication(publication_id, name, code, creation_date,
> update_date, last_user_id, status, transmit_app, application_type,
> flags)values(@.maxPubId, @.name, @.pubCode, getDate(), getDate(), 13, 1, 1, 1
,0)
> @.pubId=@.maxPubId+1
> end
> return
> --
> bic|||Thanks so much. You've solved a problem which plagued me for better part of
today. Thanks again.
--
bic
"bic" wrote:

> I can't seem to figure out why this SP would not compile. Your assistance
is
> much appreciated.
> CREATE PROCEDURE sp_getPubId
> @.name varchar, @.pubCode varchar, @.pubId smallint Output
> AS
> DECLARE maxPubId smallint
> if (exists
> (select publication_id from publication where code =@.pubCode))
> begin
> @.maxPubId=(select publication_id from publication where code =@.pubCode)
> @.pubId=@.maxPubId
> end
> else begin
> @.maxPubId=select max(publication_id) from publication
> insert into publication(publication_id, name, code, creation_date,
> update_date, last_user_id, status, transmit_app, application_type,
> flags)values(@.maxPubId, @.name, @.pubCode, getDate(), getDate(), 13, 1, 1, 1
,0)
> @.pubId=@.maxPubId+1
> end
> return
> --
> bic

IF ELSE alternative for stored procedure

Hi,

I'm trying to create a stored procedure that checks to see whether the parameters are NULL. If they are NOT NULL, then the parameter should be used in the WHERE clause of the SELECT statement otherwise all records should be returned.

sample code:

SET ANSI_NULLSONGOSET QUOTED_IDENTIFIERONGOCREATE PROCEDURE [dbo].[GetProjectInfo](@.ProjectTitlevarchar(300), @.ProjectManagerIDint, @.DeptCodevarchar(20), @.ProjIDvarchar(50), @.DateRequesteddatetime, @.DueDatedatetime, @.ProjectStatusIDint)ASBEGINSET NOCOUNT ONIF @.ProjectTitleISNOT NULL AND @.ProjectManagerIDISNULL AND @.DeptCodeISNULL AND @.ProjIDISNULL AND @.DateRequestedISNULL AND @.DueDateISNULL AND @.ProjectStatusIDISNULLSELECT ProjID, ProjectTitle, ProjectDetails, ProjectManagerID, RequestedBy, DateRequested, DueDate, ProjectStatusIDFROM dbo.tbl_ProjectWHERE ProjectTitle = @.ProjectTitle;ELSE IF @.ProjectTitleISNOT NULL AND @.ProjectManagerIDISNOT NULL AND @.DeptCodeISNULL AND @.ProjIDISNULL AND @.DateRequestedISNULL AND @.DueDateISNULL AND @.ProjectStatusIDISNULLSELECT ProjID, ProjectTitle, ProjectDetails, ProjectManagerID, RequestedBy, DateRequested, DueDate, ProjectStatusIDFROM dbo.tbl_ProjectWHERE ProjectTitle = @.ProjectTitleAND ProjectManagerID = @.ProjectManagerID;ELSESELECT ProjID, ProjectTitle, ProjectDetails, ProjectManagerID, RequestedBy, DateRequested, DueDate, ProjectStatusIDFROM dbo.tbl_Project;

I could do this using IF-ELSE but that would require a ridiculous amount of conditional statements (basically 1 for each combination of NULLs and NOT NULLs). Is there a way to do this without all the IF-ELSEs?

Thanks.

it will be easier to dynamically build your sql string, while you'll still have to use IF-ELSE you won't have to check for each and every condition combination, just check for each parameter. for example...

CREATE PROCEDURE [dbo].[GetProjectInfo]
(@.ProjectTitlevarchar(300), @.ProjectManagerIDint, @.DeptCodevarchar(20), @.ProjIDvarchar(50),
@.DateRequesteddatetime, @.DueDatedatetime, @.ProjectStatusIDint)
AS
BEGIN
SET NOCOUNT ON

DECLARE @.strSQL varchar(4000)

SET @.strSQL = "SELECT ProjID, ProjectTitle, ProjectDetails, ProjectManagerID, RequestedBy, DateRequested, DueDate, ProjectStatusID "
SET @.strSQL = @.strSQL + "FROM dbo.tbl_Project "

SET @.strSQL = @.strSQL + "WHERE "

IF @.ProjectTitle IS NOT NULL

BEGIN

SET @.strSQL = @.strSQL + "ProjectTitle = " + @.ProjectTitle

END

IF @.ProjectManagerId IS NOT NULL

BEGIN

SET @.strSQL = @.strSQL + " AND ProjectMangerId = " + @.ProjectMangerId

END

<conditions for each param>

EXEC(@.strSQL)

GO

|||

There is a better way than using lots of IF and ELSE statements. Rewrite your stored proecedure so that it doesn't matter what parameters are passed it will always work. eg.


CREATEPROCEDURE [dbo].[GetProjectInfo]

(

@.ProjectTitlevarchar(300)=NULL, @.ProjectManagerIDint=NULL, @.DeptCodevarchar(20)=NULL,

@.ProjID

varchar(50)=NULL, @.DateRequesteddatetime=NULL, @.DueDatedatetime=NULL, @.ProjectStatusIDint=NULL)

AS

BEGIN

SET

NOCOUNTONSELECT ProjID, ProjectTitle, ProjectDetails, ProjectManagerID, RequestedBy, DateRequested, DueDate, ProjectStatusIDFROM dbo.tbl_ProjectWHERE(ProjectTitle= @.ProjectTitleOR @.ProjectTitleISNULL)AND(ProjectManagerID= @.ProjectManagerIDOR @.ProjectManagerIDISNULL)AND(DeptCode= @.DeptCodeOR @.DeptCodeISNULL)AND(ProjID= @.ProjIDOR @.ProjIDISNULL)AND(.... [rest of parameters])

END

|||SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[GetProjectInfo]
(@.ProjectTitle varchar(300), @.ProjectManagerID int, @.DeptCode varchar(20), @.ProjID varchar(50),
@.DateRequested datetime, @.DueDate datetime, @.ProjectStatusID int)
AS
SET NOCOUNT ON
IF DATALENGTH(RTRIM(@.ProjectTitle)) = 0 SET @.ProjectTitle = NULL
IF DATALENGTH(RTRIM(@.ProjectManagerID)) = 0 SET @.ProjectManagerID = NULL
IF DATALENGTH(RTRIM(@.ProjectStatusID)) = 0 SET @.ProjectStatusID = NULL
IF DATALENGTH(RTRIM(@.DeptCode)) = 0 SET @.DeptCode = NULL
IF @.DueDate >= CONVERT(DATETIME, '9999-12-31 00:00:00') SET @.DueDate = NULL
IF @.DateRequested >= CONVERT(DATETIME, '9999-12-31 00:00:00') SET @.DateRequested = NULL
SELECT ProjID, ProjectTitle, ProjectDetails, ProjectManagerID, RequestedBy, DateRequested, DueDate, ProjectStatusID
FROM dbo.tbl_Project
WHERE ProjectTitle = COALESCE(@.ProjectTitle, ProjectTitle)
AND ProjectManagerID = COALESCE(@.ProjectManagerID, ProjectManagerID)
AND ProjectStatusID = COALESCE(@.ProjectStatusID, ProjectStatusID)
AND DeptCode = COALESCE(@.DeptCode, DeptCode)
AND DateRequested = COALESCE(@.DateRequested, DateRequested)
AND DueDate = COALESCE(@.DueDate, DueDate)|||

The beauty of the S.P. I just posted is that it remains very simple no matter what combination of search is used. For unused string crriteria, use ''. For Integer use use 0. For dates pass a date of 31/Dec/9999.

The idea was suggested some years ago to me by Joe Celko.

|||

Woah.

Thanks for all the quick replies.

I'm away from my development machine right now, but I'll try the solutions in a few hours and let you know how it works out.

Thanks again.

|||I would recommend user "Connect"'s solution. Too many IF loops can screw up the query plan.|||

Connect:

There is a better way than using lots of IF and ELSE statements. Rewrite your stored proecedure so that it doesn't matter what parameters are passed it will always work. eg.


CREATEPROCEDURE [dbo].[GetProjectInfo]

(@.ProjectTitlevarchar(300)=NULL, @.ProjectManagerIDint=NULL, @.DeptCodevarchar(20)=NULL,

@.ProjIDvarchar(50)=NULL, @.DateRequesteddatetime=NULL, @.DueDatedatetime=NULL, @.ProjectStatusIDint=NULL)

AS

BEGIN

SETNOCOUNTON

SELECT ProjID, ProjectTitle, ProjectDetails, ProjectManagerID, RequestedBy, DateRequested, DueDate, ProjectStatusID

FROM dbo.tbl_Project

WHERE(ProjectTitle= @.ProjectTitleOR @.ProjectTitleISNULL)

AND(ProjectManagerID= @.ProjectManagerIDOR @.ProjectManagerIDISNULL)

AND(DeptCode= @.DeptCodeOR @.DeptCodeISNULL)

AND(ProjID= @.ProjIDOR @.ProjIDISNULL)

AND(.... [rest of parameters])

END

I was going over the code you posted, and it occurred to me that I made a *slight* error.Tongue Tied


The ProjID is actually of the form DeptCode-Number (e.g. ACCT-1) and I don't have the DeptCode field in my tbl_Project.

Basically, I want to do something like:

CREATE PROCEDURE [dbo].[GetProjectInfo](@.ProjectTitlevarchar(300) =NULL, @.ProjectManagerIDint =NULL, @.DeptCodevarchar(20) =NULL,@.ProjIDvarchar(50) =NULL, @.DateRequesteddatetime =NULL, @.DueDatedatetime =NULL, @.ProjectStatusIDint =NULL)ASBEGINSETNOCOUNT ONSELECT ProjID, ProjectTitle, ProjectDetails, ProjectManagerID, RequestedBy, DateRequested, DueDate, ProjectStatusIDFROM dbo.tbl_ProjectWHERE (ProjectTitle = @.ProjectTitleOR @.ProjectTitleISNULL)AND (ProjectManagerID = @.ProjectManagerIDOR @.ProjectManagerIDISNULL)--AND (DeptCode = @.DeptCode OR @.DeptCode IS NULL)AND ((IF @.DeptCodeISNOT NULL ProjID = @.DeptCode +'-' +'%')ELSE ProjID = @.ProjIDOR @.ProjIDISNULL)-- OR @.DeptCode IS NULL))AND (DateRequested = @.DateRequestedOR @.DateRequestedISNULL)AND (DueDate = @.DueDateOR @.DueDateISNULL)AND (ProjectStatusID = @.ProjectStatusIDOR @.ProjectStatusIDISNULL)END


which is to say,

if @.DeptCode is not null, ProjID = @.DeptCode + '-' + (any number)

else ProjID = @.ProjID

I tried the code I posted, but understandably I get errors of Incorrect syntax near keyword IF an near ProjID.

Thanks again.

|||

Hi,

I was wondering if someone could help me out with the problem of implementing

IF @.DeptCode IS NOT NULL

ProjID = @.DeptCode + '-' + (any number)

ELSE ProjID = @.ProjID

in the code given by Connect.

Thanks.


|||

Try something like this:

CREATE PROCEDURE [dbo].[GetProjectInfo](@.ProjectTitlevarchar(300) =NULL, @.ProjectManagerIDint =NULL, @.DeptCodevarchar(20) =NULL,@.ProjIDvarchar(50) =NULL, @.DateRequesteddatetime =NULL, @.DueDatedatetime =NULL, @.ProjectStatusIDint =NULL)ASBEGINSET NOCOUNT ONDeclare @.nintIF @.DeptCodeISNOT NULLSET @.Deptcode = @.Deptcode +'-' +convert(varchar,@.n)SELECT ProjID, ProjectTitle, ProjectDetails, ProjectManagerID, RequestedBy, DateRequested, DueDate, ProjectStatusIDFROM dbo.tbl_ProjectWHERE (ProjectTitle = @.ProjectTitleOR @.ProjectTitleISNULL)AND (ProjectManagerID = @.ProjectManagerIDOR @.ProjectManagerIDISNULL)--AND (DeptCode = @.DeptCode OR @.DeptCode IS NULL)AND (ProjID =CaseWHEN @.DeptcodeISNOT NULLTHEN @.DeptCodeELSE @.ProjIDEND)--AND ((IF @.DeptCode IS NOT NULL ProjID = @.DeptCode + '-' + '%') ELSE ProjID = @.ProjID OR @.ProjID IS NULL)-- OR @.DeptCode IS NULL))AND (DateRequested = @.DateRequestedOR @.DateRequestedISNULL)AND (DueDate = @.DueDateOR @.DueDateISNULL)AND (ProjectStatusID = @.ProjectStatusIDOR @.ProjectStatusIDISNULL)END

|||

Hi,

Thanks for the reply.

The code you posted doesn't seem to work. Now I get 0 rows returned when using any of the parameters.

|||

I did not set any value for @.n. You just mentioned "number" but didnt say what number? does it come from a lookup table/user? For example:

SET @.n = 4

right before the check for NULL on @.Deptcode.

|||

oh. What I meant by number was, any number using a wildcard. The only wildcard I know for sql is '%', that's why if you see my example code, I did the following

ProjID = @.DeptCode + '-' + '%'

I don't know if that would work, but it shows the general idea.

|||I dont understand..can you provide some sample parameters and how you expect the ProjID to turn out?|||

sure. Let's say I run the code given below:

DECLARE@.return_valueintEXEC@.return_value = [dbo].[GetProjectInfo]@.ProjectTitle =NULL,@.ProjectManagerID =NULL,@.DeptCode ='BAT',@.ProjID =NULL,@.DateRequested =NULL,@.DueDate =NULL,@.ProjectStatusID =NULLSELECT'Return Value' = @.return_valueGO
 
I would want that to return all records where the ProjID = BAT-*
That is, all records that have the word BAT as the first part of the ProjID. 

Wednesday, March 21, 2012

Identity vs. Identity(1,1)

Is there a difference in the resulting values for the identity fields if I
create a table and specify one of the following:
CREATE TABLE #Temp (TempID int identity, Description(100) )
CREATE TABLE #Temp (TempID int identity(1,1), Description(100) )
In other words, if (1,1) is not specified after declaring a field as identity,
is (1,1) the assumed default?
--
Message posted via http://www.sqlmonster.comHi cbrichards
BOL says that "You must specify both the seed and increment or neither.
If neither is specified, the default is (1,1)." identity by itself
should be the same as identity(1,1)
When you insert a few records into each table and selected them back
out, what do you get?
CREATE TABLE #Temp (TempID int identity, Description varchar(100) )
GO
INSERT #temp DEFAULT VALUES
GO 10
SELECT * FROM #temp
DROP TABLE #temp
CREATE TABLE #Temp (TempID int identity(1,1), Description
varchar(100) )
GO
INSERT #temp DEFAULT VALUES
GO 10
SELECT * FROM #temp
DROP TABLE #temp
KenJ
cbrichards via SQLMonster.com wrote:
> Is there a difference in the resulting values for the identity fields if I
> create a table and specify one of the following:
> CREATE TABLE #Temp (TempID int identity, Description(100) )
> CREATE TABLE #Temp (TempID int identity(1,1), Description(100) )
> In other words, if (1,1) is not specified after declaring a field as identity,
> is (1,1) the assumed default?
> --
> Message posted via http://www.sqlmonster.com|||Yes, if you are not specifying the value then it will be defaulted to (1,1)
Thanks
Hari
"cbrichards via SQLMonster.com" <u3288@.uwe> wrote in message
news:6a0b564bac5a5@.uwe...
> Is there a difference in the resulting values for the identity fields if I
> create a table and specify one of the following:
> CREATE TABLE #Temp (TempID int identity, Description(100) )
> CREATE TABLE #Temp (TempID int identity(1,1), Description(100) )
> In other words, if (1,1) is not specified after declaring a field as
> identity,
> is (1,1) the assumed default?
> --
> Message posted via http://www.sqlmonster.com
>

Monday, March 19, 2012

Identity Ranges

I'm using Merge replication on a database that was designed using integer identity columns for primary keys. When I create a publisher it's great because Sql Server will create rowguid columns for me on most of the tables; actually all but one table.

The problem comes when I try and use identity ranges for the subscribers. As a test I set up a range on one table, it only allowed for 10 in the range with an 80% threshold. I wanted to see what would happen when say my publisher db inserts 11 new rows. Well, I found out that after the 8th new row it wouldn't insert anymore as the range was exceeded and it gave me an error message saying
The identity range managed by replication is full and must be updated by a replication agent.

The question is; which agent needs to run in order for the new range to be assigned to the publisher? I have seen some people talk about an sp_ that can be run, but in a production environment I wont this to be automatic.

My altenative to ranged identies is using guid uniqueidentifiers. See my other post on this!!

regards

GrahamI assume this is SQL Server 2000.

To answer your questions:
Maybe the table on which merge is not adding the rowguid col is because the table already has a rowguid column?

And since you have 80% threashold, it is failing after the 8th row and I assume you have pub_idrange and range values each set to 10.
You can get by this situation by increasing the numbers, so that the probablity of them running out of numbers is less. Say like 10,000 or 100,000.

And the agent to be run when the id range is full is the merge agent. Running the merge agent will refresh the ranges on publisher and subscriber.
On the publisher, you can also run the sp_adjustpublisheridentityrange to refresh the range and that way you dont need to run the merge agent.

But typically in a production scenario, it is recommended that:
1. You have a decent sized value for the publisher and subscriber id range values
2. Merge agent to run frequently. That way the ranges will be refreshed (if needed) when merge agent runs.

Identity property

Hello friends,

I am using sql server 2005. In some tables to create the column Autoincrement I had set the 'Idetity Specification' property to 'Yes'. I want to know that how can we do it through sql scripts i.e. by writing query.

Please let me know

Thanks & Regards
Girish Nehte

CREATE TABLE your_table( id_numint IDENTITY(1,1), fnamevarchar (20), minitchar(1), lnamevarchar(30))
PS: IDENTITY(seed, increment)|||

Thanks Addie.

Actually I have already build table and its identity field for id column is already set to "Yes". Now what I want to do is create a script which when executed will first set identity field to "No" and then again to "Yes", i.e. I want to alter that table.

How it can be done?

Thanks & Regards
Girish Nehte

|||T-SQL's ALTER TABLE statement doesn't support dropping the IDENTITY property in SQL Server 2000 or 7.0. Your only option for deleting an IDENTITY column is to create a new table structure without the IDENTITY column, then copy the data into this structure.

Just curious - why would you like to do that?

|||

I suspect what you want to do is to turn off the auto increment on the identity column so you can insert your own values. To do that, use

SETIDENTITY_INSERT tablenameOFF

then populate the table and issue

SETIDENTITY_INSERT tablenameON

|||

Actually in my project I want to create a script after running that script all the data from the data will be deleted and columns with identity "YES" will be reset to 0. Thats why and I think that it can be done by setting and resetting the identity field.

|||

Try:

1. using the truncate statement instead of delete (ex: TRUNCATE TABLE theNameOfYourTable)
2. EXEC ('DBCC CHECKIDENT(theNameOfYourTable,RESEED,0)')

Monday, March 12, 2012

IDENTITY on a BitMap column?

Consider the following table
CREATE TABLE Attributes( id int identity(1,1),
name varchar(100),
mask bigint)
Now, attribute mask will be a bit mask of the attribute name. Consider the
data:
id name mask
-- -- --
1 foo 1
2 bar 2
3 mann 4
4 frau 8
5 kein 16
6 alles 32
How do I put a trigger on this table, or something so that I do not have to
worry about the mask when I insert data? Inserting 1 record at a time would
be no problem, just get the MAX of mask and double it. But how to handle
two or more inserts at a time? Should I use an instead-of-trigger?
Sorry about the poor english.
Dieter"Dieter Katzenland" <deiter@.rrtc.com> wrote in
news:#e8DYffjDHA.2964@.tk2msftngp13.phx.gbl:
> How do I put a trigger on this table, or something so that I do not
> have to worry about the mask when I insert data? Inserting 1 record
> at a time would be no problem, just get the MAX of mask and double it.
> But how to handle two or more inserts at a time? Should I use an
> instead-of-trigger?
hi,
in this case it would be enough to let the mask empty on inserting and then
use an AFTER INSERT Trigger for calculating the mask.
--
best regards
Peter Koen
--
MCAD, CAI/R, CAI/S, CASE/RS, CAT/RS
http://www.kema.at|||Assuming that your multi-row INSERT originates from a table or query:
CREATE TABLE foo (name VARCHAR(10) PRIMARY KEY)
INSERT INTO foo VALUES ('Alpha')
INSERT INTO foo VALUES ('Beta')
INSERT INTO Attributes (id, name, mask)
SELECT COUNT(*)+
(SELECT MAX(id) FROM attributes),
A.name,
POWER(2,COUNT(*))*
(SELECT MAX(mask) FROM attributes)
FROM foo AS A
JOIN foo AS B
ON A.name >= B.name
GROUP BY A.name
--
David Portas
--
Please reply only to the newsgroup
--

identity inserts

Hey All,

I was trying to use a typed dataset to create a very simple DAL. I found that the code generated for the INSERT statement includes an identity field the table has. That can obviously never work (unless identity_insert is set, which it is not). My question is whether it is possible to control this insert statement generation? Is there a property I am missing somewhere? My solution was to change the INSERT statement on the DataTableAdapter, but that seems awkward for me to have to do that..

Thanks,

Yuval

From SQL side you can turn on an option to enable identity inserts to a table:

SET IDENTITY_INSERT ONmyTable

Then you can insert values specifying columns and identity value:

INSERT INTOmyTable (id,name) VALUES(100, 'Iori')

Note: this is a session option, which means you have to turn on this option for every connection you want to insert identity values. For more information about this option, please refers to

http://msdn.microsoft.com/library/en-us/tsqlref/ts_set-set_7zas.asp?frame=true

|||In my post, I actually said that this is not what I am trying to achieve. The problem is that the dataset generates an insert statement that includes the identity column and I have to edit it to not do that.|||Sorry for misunderstood you:)I've no idea of your issue, waiting for right answer...

Friday, March 9, 2012

Identity constraint - Drop Create dynamically?

Greetings all,

I have an identity field that I need to drop the constraint and recreate it inside a stored procedure. Actually if there is a better way to do what I'm trying to do, I'm all ears.

My concern is that the 2^31 will eventually be exceeded on the int declaration for this field and I'm not using the field for anything other than to identify uniqueness for a specific task.

What I would like to do is re-number this field each time the table is populated. (not remember the last index)Once I'm finished with the table, I'd like the constraint to be removed.

Any thoughts?

Adamus

The only 'real' option is to drop the existing IDENTITY field, and recreate a new one.|||

I was leaning that way.

Thank you,

Adamus