How can I create table not declare column but copy from another? - sql

I want to create a stored procedure to return all column data from a table except one column that key of where condition. The original table will be change a lot during my project, so I don't want to create table with declaring columns. How can I create the table that columns are copy of another table? I'm using SQL Server.
ALTER PROCEDURE [dbo].[SelectCharacterDataById]
#Id INT
AS
BEGIN
SET NOCOUNT ON;
CREATE TABLE #TempTable
AS
SELECT *
FROM dbo.CharacterData
WHERE CharacterID = #Id
ALTER TABLE #TempTable
DROP COLUMN CharacterID
SELECT *
FROM #TempTable
END

Related

How we can add column in sql server with auto generated record insertion number. if Index are defined on that table

My database(SQL server 2008) already having some records and having two sorting index on two columns. I tried to add identity column using following query. But it providing me wrong identity numbers associated with records.
alter table Table_name add RECORD_NUMBER int identity(1,1)
record which inserted first having higher number and record which is inserted last having lower number. and some records are having just opposite numbers. Is it possible to remove such kind of problem and insert right insertion order for records.
I did this because i was not having any primary key or unique or compost key in my table. So to identify which record is first entered, i introduce identity column. I was thinking that it will allocate record number according to insertion order.
If it's possible for you to move data in a new table then this is an approach which is basically recommended by Microsoft:
/*************
Preparing for the example, create tables, insert sample data,...
**************/
-- Your existing table
CREATE TABLE dbo.oldtable
(
colA int,
colB nvarchar(10)
)
-- The new table, same structure + new identity column:
CREATE TABLE dbo.newtable
(
colID int IDENTITY(1,1),
colA int,
colB nvarchar(10)
)
--create unique clustered index on new identity column
create unique clustered index ucx_newtable
on dbo.newtable (colID ASC)
--create other indexes as you need them
create index idx_newtable
on dbo.newtable (colA ASC)
--sample data
insert into dbo.oldtable(colA,colB)
values (16,'this'),(17,'is'),(225,'an'),(300,'example')
/*************
Data Movement
**************/
BEGIN TRANSACTION
BEGIN TRY
--move data to new table including new id column which is generated by
--colA, which gives us the order from old to new in this example
SET IDENTITY_INSERT dbo.newtable ON --So we can insert into the colID identity column
INSERT INTO dbo.newtable(colID, colA,colB)
SELECT ROW_NUMBER() OVER(ORDER BY colA ASC) AS colID --this will generate numbers beginning from 1
,colA, colB
FROM dbo.oldtable
SET IDENTITY_INSERT dbo.newtable OFF
--rename old table / or drop it if you want
EXEC sp_rename #objname = 'dbo.oldtable', #newname = 'dbo.oldtable_xyz'
EXEC sp_rename #objname = 'dbo.newtable', #newname = 'dbo.oldtable'
COMMIT TRANSACTION
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE()
ROLLBACK TRANSACTION
END CATCH

Add identity increment property to existing tables at once

I have multiple tables in database all table has id column which is primary key.
I want a script by which i can add identity property to all tables at once rather than I go and change one by one.
You can't alter the existing columns for identity.
You have 2 options:
Create a new table with identity & drop the existing table
Create a new column with identity & drop the existing column
But take spl care when these columns have any constraints / relations.
For already craeted table Names
Drop table Names
Create table Names
(
ID int,
Name varchar(50)
)
Insert Into Names Values(1,'SQL Server')
Insert Into Names Values(2,'ASP.NET')
Insert Into Names Values(4,'C#')
In this Approach you can retain the existing data values on the newly
created identity column
CREATE TABLE dbo.Tmp_Names
(
Id int NOT NULL IDENTITY (1, 1),
Name varchar(50) NULL
) ON [PRIMARY]
go
SET IDENTITY_INSERT dbo.Tmp_Names ON
go
IF EXISTS(SELECT * FROM dbo.Names)
INSERT INTO dbo.Tmp_Names (Id, Name)
SELECT Id, Name FROM dbo.Names TABLOCKX
go
SET IDENTITY_INSERT dbo.Tmp_Names OFF
go
DROP TABLE dbo.Names
go
Exec sp_rename 'Tmp_Names', 'Names'
In this approach you can’t retain the existing data values on the
newly created identity column;
The identity column will hold the sequence of number
Alter Table Names Add Id_new Int Identity(1,1)
Go
Alter Table Names Drop Column ID
Go
Exec sp_rename 'Names.Id_new', 'ID','Column'
Source 1
What you can do is write a quick query to generate the SQL for you
like so:
USE INFORMATION_SCHEMA;
SELECT
CONCAT("ALTER TABLE `", TABLE_SCHEMA,"`.`", TABLE_NAME, "` CONVERT TO CHARACTER SET UTF8;")
AS MySQLCMD FROM TABLES
WHERE TABLE_SCHEMA = "your_schema_goes_here";
Then you can run the output from this to do what you need.
Source 2
EDIT
You could check Altering Multiple Tables at once

Create a temporary table in SQL on the fly

How can I create a temporary table without first creating the columns?
CREATE TABLE #Yaks (
YakID int,
YakName char(30) )
select name
from tempdb..sysobjects
where name like '#yak%'
drop table #yaks
It is a pain to have to define the table first.
Create a (temp) table with the same columns as another (no data copied):
select * into #TempTable
from MyTable
where 1=0
Note: Does not create any Foreign keys, indexes etc...

Drop a temporary table if it exists

I have two lines of code in SQL that create two tables on the fly, i need to do something like
IF TABLE EXISTS
DROP IT AND CREATE IT AGAIN
ELSE
CREATE IT
my lines are the following ones
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
how can I apply that concept for these two tables in my procedure?
From SQL Server 2016 you can just use
DROP TABLE IF EXISTS ##CLIENTS_KEYWORD
On previous versions you can use
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
/*Then it exists*/
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD
(
client_id INT
)
You could also consider truncating the table instead rather than dropping and recreating.
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
TRUNCATE TABLE ##CLIENTS_KEYWORD
ELSE
CREATE TABLE ##CLIENTS_KEYWORD
(
client_id INT
)
Check for the existence by retrieving its object_id:
if object_id('tempdb..##clients_keyword') is not null
drop table ##clients_keyword
What you asked for is:
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
BEGIN
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
END
ELSE
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
BEGIN
DROP TABLE ##TEMP_CLIENTS_KEYWORD
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
END
ELSE
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
Since you're always going to create the table, regardless of whether the table is deleted or not; a slightly optimised solution is:
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
DROP TABLE ##TEMP_CLIENTS_KEYWORD
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)

Can I insert into a temp table the result of a stored procedure plus another value?

I have a temp table that needs the values of a Stored procedure. So the SP inserts 3 columns into the temp table, then I want to add a datetime to every row without modifying the SP.
Since I call the SP 3 times, each time with a different datetime, I can't just update the whole temp table.
Any Suggestions?
DECLARE #temp TABLE
(
id INT IDENTITY(1,1),
Name VARCHAR(150),
Address VARCHAR(25),
Date DATETIME
)
WHILE (#count>=#daysBack)
BEGIN
SET #date=DATEADD(dd, #count, GETDATE())
INSERT INTO #temp (Name,Address)
EXEC[dbo].StoredProc#date
--I Want to check for Null and insert the date there
Update #temp SET Date=#date WHERE Date=''
SET #count=#count-1
Yes. Create the temp table and in the added date column that does not have representation from your sproc put a default value constraint of getdate() or whatever date formula you need. In the insert statement specify the columns explicitly and omit the date column and it should work. As the rows are added the default value constraint will kick in and fill that column for you.
example:
create table #tmp (c1 int, c2 int, dt datetime default(getdate()) )
insert into #tmp
(c1, c2)
exec mysproc