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
Related
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))) + ...
I am trying to create a procedure in my SQL Server Management Studio.
I wrote this code:
CREATE PROCEDURE [dbo].[InsertBookDetails_Sp]
#BookName VARCHAR(100),
#Author VARCHAR(100),
#Publisher VARCHAR(100),
#Price DECIMAL(18,2),
#BookPic VARBINARY(MAX) = NULL,
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO BookDetails(BookName, Author, Publisher, Price, BookPic)
VALUES (#BookName, #Author, #Publisher, #Price, #BookPic)
END
but it shows error
Incorrect syntax near 'As'.
Invalid ObjectName BookDetails
Invalid Column name BookName
Invalid Column name Author
Invalid Column name Publisher
Invalid Column name Price
Invalid Column name BookPic
How to solve this error?
The last parameter should not have ",". Remove the extra "," and try:
CREATE PROCEDURE [dbo].[InsertBookDetails_Sp]
#BookName VARCHAR(100),
#Author VARCHAR(100),
#Publisher VARCHAR(100),
#Price DECIMAL(18, 2),
#BookPic VARBINARY(MAX) = NULL
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO BookDetails
(BookName, Author, Publisher, Price, BookPic)
VALUES
(#BookName, #Author, #Publisher, #Price, #BookPic);
END
problem solved by removing comma near As
I am getting the Invalid object name 'CUSTOMER_temp'. Error code. I made these two tables and made the temporary table. Also when I put state from inserted. It gives me the error code Invalid column name 'state'. I am not sure if I need this still or if I am able to get rid of it.
The purpose of this trigger is to automatically copy new records to a new table.
DROP TABLE CUSTOMER
CREATE TABLE CUSTOMER
(
CustomerID CHAR(5) PRIMARY KEY, --Make Primary Key
CustLastName VARCHAR(20),
CustFirstName VARCHAR(20),
CustStreet VARCHAR(60),
CustCity VARCHAR(30),
CustState CHAR(2),
CustZip CHAR(5),
CustPhone CHAR(10),
CustEmail CHAR(50),
);
drop table CUSTOMER_temp
CREATE TABLE CUSTOMER_temp -- temporary table
(
CustomerID CHAR(5) PRIMARY KEY,
CustLastName VARCHAR(20),
CustFirstName VARCHAR(20),
CustStreet VARCHAR(60),
CustCity VARCHAR(30),
CustState CHAR(2),
CustZip CHAR(5),
CustPhone CHAR(10),
CustEmail CHAR(50),
);
CREATE TRIGGER dbo.CustCopy
On CUSTOMER
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
insert CUSTOMER_temp (CustomerID, CustLastName, CustPhone, CustState)
Select CustomerID, CustLastName, CustPhone, CustState from inserted
END
Try this... You need INTO after the Insert.
UPDATE removed dbo.
CREATE TRIGGER dbo.CustCopy
On CUSTOMER
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
insert INTO CUSTOMER_temp (CustomerID, CustLastName, CustPhone, CustState)
Select CustomerID, CustLastName, CustPhone, CustState from inserted
END
I am creating a stored procedure to check if username exists and if does not exists insert into user table then gets userid for the same username. This is what I was trying
alter Procedure Check_Name
(--#idn integer,
#username varchar(25),
#password varchar(100)
--#role_id integer)
As
Begin
INSERT INTO [user] (username, [password])
SELECT
username, [password]
FROM
[user] AS u
WHERE
NOT EXISTS(SELECT * FROM [user] AS t
WHERE u.username = t.username);
End
When I try to execute it says zero rows affected.. What is the problem?
execute Check_Name 'Pope', 'Life2Stressfull';
Perhaps you intend something like this:
Insert into user(username, password, role_id, date)
Select #username, NULL, NULL, getdate()
from user
Where Not Exists(Select * from user where username = #username);
However, I would recommend putting a unique index on user(username) and then using a try/catch block to capture any errors. I don't think a separate transaction is needed.
There are a couple of things confusing me at this level.
I have a table with around 40 columns out of which atleast 35 are in where clause at different times in single execution of a procedure.
When these 35 columns are passed a value via stored procedure, the stored procedure call their respective inline TVF's which in turn call a common multiline TVF.
I need to know if I shall consider creating indexes for all these 35 columns (Though I have serious doubts if that can help, but please tell me I am wrong if it does. )
I am inserting data into a Temporary table . This insert goes on for number of parameters passed to stored procedure and execution plan shows it takes quite a considerable amount of time. Is there a way I can improve the performance here ?
The insert query looks like this :
INSERT INTo #Temp2
(RowNumber,ValFromUser,ColumnName,ValFromFunc,FuncWeight,percentage)
SELECT RowNumber,#firstname,'firstname',PercentMatch,
#constVal,PercentMatch * #constVal FROM dbo.MatchFirstName(#firstname)
:
Execution plan is attached :
execution plan
Table with large number of columns is as follows :
create table Patients
(
Rowid int identity(1,1),
firstname nvarchar(20) not null,
middlename nvarchar(20),
lastname nvarchar(20)not null,
DOB Date,
SSN nvarchar(30),
ZIP nvarchar(10),
[State] nvarchar(2),
City nvarchar(20),
StreetName nvarchar(20),
StreetType nvarchar(20),
BuildingNumber int,
Aptnumber nvarchar(10),
patientnickname nvarchar(20),
patientsMaidenlastname nvarchar(20),
fathersFirstName nvarchar(20),
fatherslastname nvarchar(20),
mothersfirstname nvarchar(20),
motherslastname nvarchar(20),
mothersMaidenlastname nvarchar(20),
citizenship nvarchar(20),
nationality nvarchar(20),
ethnicity nvarchar(20),
race nvarchar(20),
religion nvarchar(20),
primarylanguage nvarchar(20),
patientmrn nvarchar(30),
hospitalname nvarchar(30),
Medicaidid nvarchar(10),
pcpnpi nvarchar(10),
phonenumber nvarchar(15),
email nvarchar(30),
CreatedAt datetime default getdate(),
ModifiedAt datetime DEFAULT getdate(),
CreatedBy nvarchar(128) default SUSER_NAME(),
ModifiedBy nvarchar(128) default SUSER_NAME()
);
Temporary table looks like this :
create table #Temp2
(
Rownumber int not null,
ValFromUser nvarchar(30),
ColumnName nvarchar(30),
ValFromFunc decimal(18, 4),
FuncWeight decimal(18, 4),
Percentage decimal(18, 4) not null,
);
ResultsStored table :
create table ResultsStored
(
Sno int identity(1,1),
SearchSerial int,
StringSearched varbinary(8000),
RowId int,
PercentMatch decimal(18,4),
CreatedAt datetime default getdate(),
ModifiedAt datetime default getdate(),
CreatedBy nvarchar(128) default SUSER_Name(),
ModifiedBy nvarchar(128) default SUSER_NAME(),
HashedKey binary(16)
);
Indexes speed up (sometimes) SELECTs. But indexes slow down INSERTs (and also DELETEs, UPDATEs etc.). So it's a bad idea to have too many indexes.
Quite often SELECT is able to use only one index (or even zero). So all other 34 indexes are nothing of help. Keep only those ones your SELECTs really use.
As you say, you have about 40 columns in a table with at least 35 columns are being mentioned in distinct 'WHERE'-clauses. That is your table not just big, but, which is far worse, it has too many potential keys. It's a very bad design. You need to split it to several tables. Read about normalization.