I have a table called tbRep in my database
I have 3 schemas on the the SQL Server database
X, Y, Z
now X & Y have tables called X.tbRep & Y.tbRep
However, when I try use the CREATE To script from e.g. X.tbRep and try to create one for the new schema Z, it throws an error saying,
Msg 2714, Level 16, State 6, Line 2
There is already an object named 'tbRep' in the database.
What am I doing wrong here?
I'm sure that there are Z.tbRep doesn't exist
CREATE to script
USE [Info]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [Z].[tbRep](
[ReplicaGroup] [varchar](50) NOT NULL,
[RunFrequencyUnit] [char](1) NOT NULL,
[Enabled] [bit] NOT NULL,
[LastRun] [datetime] NOT NULL,
[RunFrequency] [int] NOT NULL,
[ReplicationWindowType] [char](1) NOT NULL,
[ReplicationWindowSize] [tinyint] NOT NULL,
CONSTRAINT [PK_tbReplicaGroups] PRIMARY KEY CLUSTERED
(
[ReplicaGroup] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [Z].[tbReplicaGroups] ADD CONSTRAINT [DF_tbReplicaGroups_ReplicationWindowType] DEFAULT ('D') FOR [ReplicationWindowType]
GO
ALTER TABLE [Z].[tbReplicaGroups] ADD CONSTRAINT [DF_tbReplicaGroups_ReplicationWindowSize] DEFAULT ((1)) FOR [ReplicationWindowSize]
GO
--Checks to see if the table doesn't already exist, if not add your creation script
if not exists (select name from sys.tables where name = 'tpRep')
BEGIN
--Table Creation code goes here
END
Can you execute this before CREATE TABLE statement and let us know if you are getting anything?
select *
from sys.all_objects
where sys.all_objects.name = 'tbRep' and
sys.all_objects.type = 'U' and
sys.all_objects.schema_id = (select schema_id from sys.schemas where sys.schemas.name = 'Z')
Related
I want to left join but only if it does not have the specific child.
Here is my current query:
SELECT "chatRoom"."id" as id,
"chatRoom"."name" as name,
"chatRoom"."type" as type,
"chatRoom"."description" as description,
"chatRoom"."thumbnail" as thumbnail,
"chatRoom"."status" as status,
chats.[unreadCount] as unreadCount
FROM "chat_room" "chatRoom"
LEFT JOIN "chat_room_participant" "participants" ON "participants"."chatRoomId"="chatRoom"."id"
LEFT JOIN (
SELECT "chatRoom"."id" AS "chatRoomId", COUNT(readBy.id) AS "unreadCount"
FROM "chat" "chat"
LEFT JOIN "chat_room" "chatRoom" ON "chatRoom"."id"="chat"."chatRoomId"
LEFT JOIN "chat_read_by_chat_room_participant" "chat_readBy" ON "chat_readBy"."chatId"="chat"."id"
LEFT JOIN "chat_room_participant" "readBy" ON "readBy"."id"="chat_readBy"."chatRoomParticipantId"
WHERE NOT(readBy.UserId IN ('ca774a5f-a04d-ec11-ae58-74d83e04f9d3'))
OR "readBy"."id" IS NULL
GROUP BY "chatRoom"."id"
) "chats" ON chats.chatRoomId = "chatRoom"."id"
WHERE ('ALL' = 'ALL' OR "chatRoom"."status" = 'ALL')
AND "chatRoom"."applicationId" = '4ac752e9-004c-ec11-ae53-74d83e04f9d3'
AND "participants"."userId" = 'A97D66C4-014C-EC11-AE53-74D83E04F9D3'
ORDER BY "chatRoom"."lastUpdate" DESC
In this query, it returns the correct value only if the readBy is null or contains 1 entry which equals to the given userId.
So here I have the userId. I want to get all the unread chats count from each chatRoom that has the user as a participant.
The schema is like this:
chatRoom has many chats
chatRoom has many participants
chats has many to many `readBy` (participants)
So there is a column automatically created for the many-to-many relation:
column: chat_read_by_chat_room_participant
Contains:
|chatId|chatRoomParticipantId|
In my query above, the left join will get any readBy from another user:
WHERE NOT(readBy.UserId IN ('ca774a5f-a04d-ec11-ae58-74d83e04f9d3')) OR "readBy"."id" IS NULL GROUP BY "chatRoom"."id") "chats" ON chats.chatRoomId = "chatRoom"."id"
which I do not want. This will return the entry if the user already read the chat, but another users have read as well. I want to return the entry only if the user has not read the chat.
How can I do this?
CREATION QUERY
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[chat](
[id] [uniqueidentifier] NOT NULL,
[sentAt] [bigint] NOT NULL,
[type] [nvarchar](255) NOT NULL,
[status] [nvarchar](255) NOT NULL,
[message] [nvarchar](max) NOT NULL,
[filePath] [nvarchar](max) NULL,
[chatRoomId] [uniqueidentifier] NOT NULL,
[senderId] [nvarchar](255) NOT NULL,
[userId] [uniqueidentifier] NULL,
CONSTRAINT [PK_9d0b2ba74336710fd31154738a5] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[chat] ADD CONSTRAINT [DF_9d0b2ba74336710fd31154738a5] DEFAULT (newsequentialid()) FOR [id]
GO
ALTER TABLE [dbo].[chat] WITH CHECK ADD CONSTRAINT [FK_52af74c7484586ef4bdfd8e4dbb] FOREIGN KEY([userId])
REFERENCES [dbo].[chat_room_participant] ([id])
GO
ALTER TABLE [dbo].[chat] CHECK CONSTRAINT [FK_52af74c7484586ef4bdfd8e4dbb]
GO
ALTER TABLE [dbo].[chat] WITH CHECK ADD CONSTRAINT [FK_e49029a11d5d42ae8a5dd9919a2] FOREIGN KEY([chatRoomId])
REFERENCES [dbo].[chat_room] ([id])
GO
ALTER TABLE [dbo].[chat] CHECK CONSTRAINT [FK_e49029a11d5d42ae8a5dd9919a2]
GO
CREATE TABLE [dbo].[chat_read_by_chat_room_participant](
[chatId] [uniqueidentifier] NOT NULL,
[chatRoomParticipantId] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_f3dd24628d4644dd6e79bcd03d1] PRIMARY KEY CLUSTERED
(
[chatId] ASC,
[chatRoomParticipantId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[chat_read_by_chat_room_participant] WITH CHECK ADD CONSTRAINT [FK_011624ccd7e7b0281ef629f2930] FOREIGN KEY([chatId])
REFERENCES [dbo].[chat] ([id])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[chat_read_by_chat_room_participant] CHECK CONSTRAINT [FK_011624ccd7e7b0281ef629f2930]
GO
ALTER TABLE [dbo].[chat_read_by_chat_room_participant] WITH CHECK ADD CONSTRAINT [FK_2e33e3de9d7c91d426c09a24810] FOREIGN KEY([chatRoomParticipantId])
REFERENCES [dbo].[chat_room_participant] ([id])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[chat_read_by_chat_room_participant] CHECK CONSTRAINT [FK_2e33e3de9d7c91d426c09a24810]
GO
CREATE TABLE [dbo].[chat_room](
[id] [uniqueidentifier] NOT NULL,
[name] [nvarchar](255) NULL,
[type] [nvarchar](255) NOT NULL,
[thumbnail] [nvarchar](max) NULL,
[description] [nvarchar](max) NULL,
[status] [nvarchar](255) NOT NULL,
[applicationId] [uniqueidentifier] NOT NULL,
[lastUpdate] [bigint] NULL,
CONSTRAINT [PK_8aa3a52cf74c96469f0ef9fbe3e] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[chat_room] ADD CONSTRAINT [DF_8aa3a52cf74c96469f0ef9fbe3e] DEFAULT (newsequentialid()) FOR [id]
GO
ALTER TABLE [dbo].[chat_room] WITH CHECK ADD CONSTRAINT [FK_2226638e6b7665ec0259d246b2b] FOREIGN KEY([applicationId])
REFERENCES [dbo].[application] ([id])
GO
ALTER TABLE [dbo].[chat_room] CHECK CONSTRAINT [FK_2226638e6b7665ec0259d246b2b]
GO
CREATE TABLE [dbo].[chat_room_participant](
[id] [uniqueidentifier] NOT NULL,
[joinedAt] [bigint] NOT NULL,
[privilege] [nvarchar](255) NOT NULL,
[chatRoomId] [uniqueidentifier] NOT NULL,
[userId] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_15913cf37a762fce4c8d6a32a42] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY],
CONSTRAINT [UQ_ae9630d66f6c5d12afd1a991fec] UNIQUE NONCLUSTERED
(
[chatRoomId] ASC,
[userId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[chat_room_participant] ADD CONSTRAINT [DF_15913cf37a762fce4c8d6a32a42] DEFAULT (newsequentialid()) FOR [id]
GO
ALTER TABLE [dbo].[chat_room_participant] WITH CHECK ADD CONSTRAINT [FK_9f718459ea81b5130f81980ca08] FOREIGN KEY([userId])
REFERENCES [dbo].[user] ([id])
GO
ALTER TABLE [dbo].[chat_room_participant] CHECK CONSTRAINT [FK_9f718459ea81b5130f81980ca08]
GO
ALTER TABLE [dbo].[chat_room_participant] WITH CHECK ADD CONSTRAINT [FK_fb664f48a4ec615ec5cce90a25d] FOREIGN KEY([chatRoomId])
REFERENCES [dbo].[chat_room] ([id])
GO
ALTER TABLE [dbo].[chat_room_participant] CHECK CONSTRAINT [FK_fb664f48a4ec615ec5cce90a25d]
GO
It looks like you just need a WHERE NOT EXISTS correlated subquery.
Don't be tempted to just use LEFT JOIN IS NULL syntax, it is generally less efficient, as it hides from the optimizer that you are doing an anti-join. Occasionally it can be useful though.
Further notes:
Don't quote column and table names unless you have to. And generally avoid names that need quoting.
Don't alias columns that don't need aliasing.
Choose short meaningful table aliases.
Basic formatting and good use of whitespace helps readability
Your LEFT JOIN chat_room_participant logically becomes an INNER JOIN because of the WHERE.
You don't need to re-join chat_room in the grouped subquery, you can just group by the join column.
You may want to use a grouped OUTER APPLY instead of that subquery. It is unlikely to get a different query plan, but it can be easier to read.
COUNT(SomeNotNullValue) is the same as COUNT(*)
('ALL' = 'ALL' OR cr.status = 'ALL') only makes sense if cr.Status is nullable, otherwise you would just use cr.status = 'ALL'. Even if it is nullable, you may as well use (cr.Status IS NULL OR cr.status = 'ALL')
SELECT
cr.id,
cr.name,
cr.type,
cr.description,
cr.thumbnail,
cr.status,
c.unreadCount
FROM chat_room cr
JOIN chat_room_participant p ON p.chatRoomId = cr.id
LEFT JOIN (
SELECT
c.chatRoomId AS chatRoomId,
COUNT(*) AS unreadCount
FROM chat c
WHERE NOT EXISTS (SELECT 1
FROM chat_read_by_chat_room_participant chat_readBy
JOIN chat_room_participant readBy ON readBy.id = chat_readBy.chatRoomParticipantId
WHERE chat_readBy.chatId = c.id
AND readBy.UserId IN ('ca774a5f-a04d-ec11-ae58-74d83e04f9d3')
)
GROUP BY c.chatRoomId
) c ON c.chatRoomId = cr.id
WHERE (cr.Status IS NULL OR cr.status = 'ALL')
AND cr.applicationId = '4ac752e9-004c-ec11-ae53-74d83e04f9d3'
AND p.userId = 'A97D66C4-014C-EC11-AE53-74D83E04F9D3'
ORDER BY
cr.lastUpdate DESC;
It seems that what you want is an anti-semi join. That is, a join to demonstrate that a row does not exist.
The two typical methods are...
main_table AS m
LEFT JOIN
other_table AS o
ON o.m_id = m.id
AND o.user = 'xyz'
WHERE
o.id IS NULL
Or...
main_table AS m
WHERE
NOT EXISTS (
SELECT *
FROM other_table AS o
WHERE o.m_id = m.id
AND o.user = 'xyz'
)
Exactly how to apply this to your example is unclear as you have cluttered your question with too many other details. (It is not a Minimal Verifiable Example.)
I'm trying to export a Matlab table containing "null" values into a SQL Server DB, without any success. Here are my DB settings in Matlab (setdbprefs command):
NullNumberRead: 'NaN'
NullNumberWrite: 'NaN'
NullStringRead: 'null'
NullStringWrite: 'null'
And two example scripts to create the test case.
To create the DB structure:
USE [master]
GO
CREATE DATABASE [TestDB]
GO
USE [TestDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TestTable](
[Field1] [int] IDENTITY(1,1) NOT NULL,
[Field2] [smallint] NULL,
[Field3] [int] NULL,
[Field4] [varchar](10) NULL,
[Field5] [datetime] NULL,
[Field6] [datetime] NULL,
[Field7] [datetime] NULL CONSTRAINT [CreatedOn_DF] DEFAULT (getdate()),
CONSTRAINT [PK_TestTable] PRIMARY KEY CLUSTERED
(
[Field1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
To insert a row from Matlab into DB:
% Connect to MS SQL Server Database
conn = database('TestDB','','','Vendor','Microsoft SQL Server',...
'Server','localhost','AuthType','Windows',...
'PortNumber',1433);
% Build record to Export (note that Field1 and Field7 are missing because
% are already generated by destination server)
R = struct('Field2', 1,...
'Field3', 10,...
'Field4', 'abc',...
'Field5', '2016-01-01 00:00:00',...
'Field6', NaN);
% Transform to Table
R = struct2table(R);
% Export to Database
datainsert(conn, '[TestDB].[dbo].[TestTable]', R.Properties.VariableNames, R);
I get the following error, while it should be allowed by Matlab DB prefs.
Error using database/datainsert (line 301)
Unable to insert element in row 1 column 5, NaN. Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
Im writing Scalar-Variable function in sql to return a strName mapped by an integer. The following is my script:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[Lookup_BSource_Value]
(
-- Add the parameters for the function here
#AVal nvarchar(100)
)
RETURNS nvarchar(100)
AS
BEGIN
-- Declare the return variable here
DECLARE #Val nvarchar(100)
SELECT #Val = Val
FROM SMBase
WHERE AName = 'a_source'
AND (OTypeCode = 1084)
AND (AVal = (#AVal))
RETURN #Val
END
I should be getting the result of "BA" but am receiving a "NULL". Is my syntax correct for the multiple AND statements?
EDIT*
Before use the function in my SSIS package I am just doing a simple
SELECT dbo.Lookup_BSource_Value(XXXXXXXXX)
This gives me the null.
The following is the logical schema of the table I am querying:
USE [MSCRM_M_RC]
GO
/****** Object: Table [dbo].[SMBase] Script Date: 1/21/2014 6:29:48 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SMBase](
[OTypeCode] [int] NOT NULL,
[AName] [nvarchar](100) NOT NULL,
[AVal] [int] NOT NULL,
[LaId] [int] NOT NULL,
[OrgId] [uniqueidentifier] NOT NULL,
[Val] [nvarchar](4000) NULL,
[DOrder] [int] NULL,
[VNumber] [timestamp] NULL,
[SMId] [uniqueidentifier] NOT NULL,
CONSTRAINT [cndx_PrimaryKey_SMap] PRIMARY KEY CLUSTERED
(
[SMId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY],
CONSTRAINT [UQ_SMap] UNIQUE NONCLUSTERED
(
[OTCode] ASC,
[AName] ASC,
[AValue] ASC,
[LaId] ASC,
[OrgId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[SMBase] ADD CONSTRAINT [DF_SMa_SMId] DEFAULT (newid()) FOR [SMId]
GO
*EDIT**
The following is my logical schema of my StringMapTable:
StringMap(SMID pk, OTypeCode,AName, AVal, LaID, OrgID fk, Val, DOrder, VNumber)
The following is my logical schema of my TPTRepair Table:
TPTRepair(TPTRepairID pk, Name, Source, TT, LTHrs, CustID fk, PID fk)
The problem is the following:
The "Source" field is an integer in TPTRepair. I'm writing the following scalar-function to reference StringMap to return the string value from Value column in StringMap. I have to have a couple ands because AName hase to = 'a_source' and OTypeCode has to = 1084.
My scalar-function results in a NULL and shouldn't be. Is my syntax correct from the multiple AND statement in my scalar-function above?
So Im apparently an idiot. It was the most simplest thing. OTypeCode was to = '10084' rather than '1084'. Im an intern. Please forgive me ;) This was the answer.
In SQL Server 2008 R2, I have a simple table with the following columns definitions:
Id (PK ,int , not null)
MeterId (FK , int ,not null)
InstallDate(DateTime, not null)
Image(NVarCharMax, null)
Number (int , not null)
Comments(NVarChar(300), null)
And Id column is set as Identity .
When I run:
insert into Transmitters (MeterId, Number, InstallDate)
values (952, 777 , '2013-02-21')
I get the duplicate key error.
There is no other transmitter with id 777 ,
There is a meter with id 952.
This started happening in more than 1 table of my DB.
Any suggestions would be most appriceated.
The entire table script is:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Transmitters](
[Id] [int] IDENTITY(1,1) NOT NULL,
[MeterId] [int] NOT NULL,
[InstallDate] [datetime] NOT NULL,
[Image] [nvarchar](max) NULL,
[Number] [int] NOT NULL,
[Comments] [nvarchar](300) NULL,
CONSTRAINT [PK_Transmitters] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Transmitters] WITH CHECK ADD CONSTRAINT [FK_Transmitter_Meter] FOREIGN KEY([MeterId])
REFERENCES [dbo].[Meter] ([Id])
GO
ALTER TABLE [dbo].[Transmitters] CHECK CONSTRAINT [FK_Transmitter_Meter]
GO
Ok , thanks guys you've been most helpful.
I've checked my identity current value using:
USE Name_Of_The_DB
GO
DBCC CHECKIDENT (‘Name_Of_The_Table’)
GO
It was indeed the cause of the problem that some rows had higher Id values than
the current identity.
Thand I inserted a row to update the current identity value:
set identity_insert YourTable ON
--Insert my row
set identity_insert YourTable OFF
Thanks :)
I have a fairly complex database that needs to be deployed to a variety of servers which may or may not potentially have existing parts of the DB already implemented on it. To work around this contingency I have setup the following test:
USE [testDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[wcSites]') AND type in (N'U'))
begin
CREATE TABLE [dbo].[wcSites](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[siteCSS] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[masterTemplate] [int] NULL,
[errorPage] [int] NULL,
[homePage] [int] NULL,
[addressProduction] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[addressTest] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[routeHandler] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[publish] [bit] NOT NULL CONSTRAINT [DF_wcSites_publish] DEFAULT ((0)),
[publicAccess] [bit] NOT NULL CONSTRAINT [DF_wcSites_publicAccess] DEFAULT ((1)),
[siteAccessPermission] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[contentOwner] [int] NULL,
[navStyle] [int] NULL,
[incScripts] [int] NULL,
[boxW] [int] NULL,
[boxH] [int] NULL,
[columns] [int] NULL,
[rows] [int] NULL,
CONSTRAINT [PK_wcSites] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [IX_wcSites_Unique_Address] UNIQUE NONCLUSTERED
(
[addressProduction] ASC,
[addressTest] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
EXEC sys.sp_addextendedproperty #name=N'MS_Description', #value=N'Ensure unique addresses in the addressProduction, addressTest fields' , #level0type=N'SCHEMA',#level0name=N'dbo', #level1type=N'TABLE',#level1name=N'wcSites', #level2type=N'CONSTRAINT',#level2name=N'IX_wcSites_Unique_Address'
end
And the end result is always:
Msg 102, Level 15, State 1, Line 32
Incorrect syntax near 'PRIMARY'.
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'end'.
If I test the IF statement, it works correctly:
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[wcSites]') AND type in (N'U'))
begin
PRINT 'Table does not exist'
end
And likewise when I test the CREATE TABLE script. But when I put the CREATE TABLE script inside of the begin..end block it fails every time. And I have the problem across the board, almost every table that uses this method fails.
Try removing the 'go' statements within the begin..end block, see if that helps.
I'm a bit hazy on the SQL Server syntax but doesn't the GO statement try to execute the Block? What happens if you replace the go with a semi-colon?
Also, the Set Ansi_padding off being in the If block while the set Ansi_padding on is outside looks odd to me, are you sure thats correct?