is is possible to do
DECLARE #guid uniqueidentifier = NEWID();
select #guid
CREATE TABLE #guid
(
[UserId] uniqueidentifier NOT NULL DEFAULT NewID(),
[FirstName] nvarchar(30),
[LastName] nvarchar(30),
[Email] nvarchar(50)
)
I am just trying this concept, if it works in will use it in my web application
the above code does not work
You can't use a dynamic table name directly, but you can first build the SQL in a string variable and execute that; the technique is known dynamic SQL:
DECLARE #guid uniqueidentifier = NEWID();
DECLARE #strSql nvarchar(max)= N'CREATE TABLE ['+cast(#guid as nvarchar(50))+']
(
[UserId] uniqueidentifier NOT NULL DEFAULT NewID(),
[FirstName] nvarchar(30),
[LastName] nvarchar(30),
[Email] nvarchar(50)
)'
select #guid
exec sp_executesql #strSql;
I have added square brackets around the table name because the default representation of a guid has hyphens in it.
If the source of the table name is not a GUID (i.e. it has the potential to contain special characters, user supplied, etc) it is good practice to clean it before using. You can use QUOTENAME() for that purpose:
... + quotename(cast(#guid as nvarchar(50))) + ...
Related
I have a table with a uniqueidentifier and NEWID() default for new records. Executed the insert script. How do I know what uniqueidentifier was generated for the Id column since the last insert?
Table Script
CREATE TABLE [dbo].[MyData](
[Id] [uniqueidentifier] NOT NULL,
[Data] [varbinary](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[MyData] ADD CONSTRAINT [DF_MyData_Id] DEFAULT (newid()) FOR [Id]
GO
Insert Script
INSERT INTO dbo.MyData (Data)
VALUES (NULL)
GO
What is the uniqueidentifier was inserted?
Use an OUTPUT clause. I INSERT the data into a table variable so that is it can consumed by other statements afterwards:
DECLARE #IDs table (ID uniqueidentifier);
INSERT INTO dbo.MyData
OUTPUT inserted.Id
INTO #IDs
DEFAULT VALUES;
SELECT *
FROM #IDs;
There is no particular value in relying on the default in your example.
Just create a scalar variable of type uniqueidentifier and assign it the result of NEWID yourself
DECLARE #Id UNIQUEIDENTIFIER = NEWID();
INSERT INTO dbo.MyData (Id)
VALUES (#Id);
This is more concise than having to insert into a table variable and subsequently select from it.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
Following code is getting error >incorrect syntax near User
CREATE PROCEDURE [dbo].[Add]
#Name NVARCHAR(50),
#Email NVARCHAR(50),
#Address NVARCHAR (300)
AS
INSERT INTO User([Name],[Email],[Address]) VALUES ("'#Name','#Email','#Address'")
RETURN 0
and tried below code too
CREATE PROCEDURE [dbo].[Add]
#Name NVARCHAR(50),
#Email NVARCHAR(50),
#Address NVARCHAR (300)
AS
INSERT INTO User VALUES ("#Name,#Email,#Address")
RETURN 0
i am using following table
CREATE TABLE [dbo].[User] (
[UserId] INT NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[Email] NVARCHAR (50) NOT NULL,
[Address] NVARCHAR (300) NULL,
PRIMARY KEY CLUSTERED ([UserId] ASC)
);
with visual studio 2019
sql server 2016 version 13.00.4001
i am not able to figure out problem
so help me out here
User is a reserved keyword in SQL Server, Use square bracket :
INSERT INTO [User] ([Name],[Email],[Address])
VALUES (#Name, #Email, #Address)
Additionally stored procedure add is also reserved. Best option is to re-name the table/sp name.
EDIT :
CREATE PROCEDURE [dbo].[Add] (
#Name NVARCHAR(50),
#Email NVARCHAR(50),
#Address NVARCHAR (300)
)
AS
INSERT INTO [User] ([Name],[Email],[Address])
VALUES (#Name, #Email, #Address)
UserId column is NOT NULL, that's why you are getting the error.
(1) Make your UserID column IDENTITY(auto increment) Or Nullable
CREATE TABLE [dbo].[User] (
[UserId] INT IDENTITY(1,1),
[Name] NVARCHAR (50) NOT NULL,
[Email] NVARCHAR (50) NOT NULL,
[Address] NVARCHAR (300) NULL,
PRIMARY KEY CLUSTERED ([UserId] ASC)
);
(2) remove Quotes from SP,
CREATE PROCEDURE [dbo].[Add]
#Name NVARCHAR(50),
#Email NVARCHAR(50),
#Address NVARCHAR (300)
AS
INSERT INTO [User]([Name],[Email],[Address]) VALUES (#Name,#Email,#Address)
RETURN 0
I know that this is a terrible practice but this is what I am being asked for. This procedure will be executed about once a month but that could change. I need the format of the new table name to be staff.20150818 which is staff.yyyymmdd. When I run my procedure, the table name is #currentDate instead of what I need it to be. In SQL Azure, I cannot use PREPARE which has been a factor in many of the solutions I have found. Here is the code I have been working on:
BEGIN
DECLARE #currentDate varchar(500);
SET #currentDate = 'staff.' +(CONVERT(VARCHAR(8),GETDATE(),3));
CREATE TABLE [dbo].[#currentDate] (
[staffID] int identity(1,1) primary key,
[firstName] nvarchar(35),
[lastName] nvarchar(35),
[positionTitle] nvarchar(45),
[leaID] nvarchar(15),
[schoolID] nvarchar(15),
[phoneNumber] nvarchar(24),
[email] nvarchar(128),
[username] nvarchar(20),
[password] nvarchar(max),
[code1] nvarchar(5),
[code2] nvarchar(5),
[date_created] datetime2(7),
[date_updated] datetime2(7)
) INSERT INTO [#currentDate](firstName, lastName, positionTitle, leaID, schoolID, phoneNumber, email, username, password, code1, code2)
SELECT firstName, lastName, positionTitle, leaID, schoolID, phoneNumber, email, username, password, code1, code2
FROM Staff
END
You just have to use dynamic SQL, Concat your SQL statement into a string, including converting the date time to varchar, then call EXEC or sp_executeSql on it.
You can't pass the table name as a variable to sp_executeSql; you need to have already resolved that in the #sql string.
Have you tried using dynamic sql?
Something like this should work :
EXECUTE sp_executesql
N'CREATE TABLE [dbo].[#currentDate] (
[staffID] int identity(1,1) primary key,
...',
N'#currentDate varchar(500)',
#currentDate = 'staff.' +(CONVERT(VARCHAR(8),GETDATE(),3))
Documentation on sp_executesql
I've seen some related posts on SO, but haven't been able to figure out what is happening here. I have a Database Project in Visual Studio 2013. Here is some code for a simple "Users" table:
CREATE TABLE [dbo].[Users]
(
[ID] BIGINT IDENTITY(1,1) NOT NULL,
[Name] NVARCHAR(50) NOT NULL,
[Email] NVARCHAR(256) NOT NULL,
[Password] BINARY(20) NOT NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED ([ID]),
CONSTRAINT [IX_Users_Email] UNIQUE ([Email]),
CONSTRAINT [CK_Users] CHECK ([dbo].[CheckUserIsValid]([Users].[Name], [Users].[Email]) = 1)
)
And here is the code for CheckUserIsValid:
CREATE FUNCTION [dbo].[CheckUserIsValid]
(
#name NVARCHAR(50),
#email NVARCHAR(256)
)
RETURNS BIT
WITH SCHEMABINDING
AS
BEGIN
IF #name = ''
OR #email = ''
OR EXISTS(SELECT 1
FROM [dbo].[BlockedEmails]
WHERE [dbo].[BlockedEmails].[Email] = #email)
OR EXISTS(SELECT 1
FROM [dbo].[ApprovalCodes]
WHERE [dbo].[ApprovalCodes].[Email] = #email)
RETURN 0
RETURN 1
END
Now, the weird part is that when I open the code files BEFORE building the project, VS does not show any errors. When I try to build it, the build fails and I get a couple of different errors:
SQL04121: Cannot find either column "dbo" or the user-defined function or aggregate "dbo.CheckUserIsValid", or the name is ambiguous. (this one is thrown on the Users table)
SQL00208: Invalid object name 'dbo.BlockedEmails'. (this one is thrown on the function)
I've read this may have something to do with how I am using a scalar function in my check constraint. Pretty stuck now though. Not sure what to try next.
UPDATE
So, if I leave the function unchanged, but change the table to:
CREATE TABLE [dbo].[Users]
(
[ID] BIGINT IDENTITY(1,1) NOT NULL,
[Name] NVARCHAR(50) NOT NULL,
[Email] NVARCHAR(256) NOT NULL,
[Password] BINARY(20) NOT NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED ([ID]),
CONSTRAINT [IX_Users_Email] UNIQUE ([Email])
)
GO
ALTER TABLE [dbo].[Users] ADD CONSTRAINT [CK_Users] CHECK ([dbo].[CheckUserIsValid]([Users].[Name], [Users].[Email]) = 1)
GO
then bizarrely it builds fine. What the heck?
This is my insert statement that I am currently using. The primary key in this table is IDNumber
ALTER procedure [dbo].[AddCustomer]
#IDNumber nvarchar(20),
#Title nchar(10),
#Name nvarchar(50),
#Surname nvarchar(50),
#CellPhone nchar(10),
#AddressLine1 nvarchar(50),
#Suburb nvarchar(40),
#City nvarchar(30),
#PostalCode nchar(10),
#EmailAddress nvarchar(50),
#Password nvarchar(20)
as
insert into Customer(IDNumber,Title,Name,Surname,CellPhone,AddressLine1,Suburb,City,PostalCode,EmailAddress,[Password])
values (#IDNumber,#Title,#Name,#Surname,#CellPhone,#AddressLine1,#Suburb,#City,#PostalCode,#EmailAddress,#Password)
Now I would like the sql statement that will prevent a duplicate email address from being inserted.
You want to look at unique constraints http://msdn.microsoft.com/en-gb/library/ms190024.aspx
ALTER TABLE Customer
ADD CONSTRAINT UC_email UNIQUE (EmailAddress);
GO
That should actually be a constraint on the table column.
ALTER TABLE Customer
ADD CONSTRAINT EmailAddress_Uniqueness_Constraint UNIQUE (EmailAddress)
You can create unique index/key on Email column.
CREATE UNIQUE INDEX IX_Email ON TABLE(EMAIL);