Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to drop all columns from my table where all records are null.
My table looks as follows:
Locations [1] [2] [3] [4] [5]
[a] 10.00 Null Null 20.00 Null
[b] Null 30.00 Null Null Null
Basically, I want to delete columns 3 and 5 from the above table. What would be the best way to do this?
Edit: Instead of manually going through the table to drop each column individually, is there a way where I can drop all columns with null records together?
Thank you.
To check if the values of a column for all rows (not records) are null you can use an aggregate such as
select max([1]), max([2])... from table
to remove a column you drop it
alter table <tablename> drop column <column name>
You could create a dynamic version of a script something like this
drop table if exists #Locations;
go
CREATE TABLE #Locations (
[Location] varchar(10) not null,
[1] decimal(12,2),
[2] decimal(12,2),
[3] decimal(12,2),
[4] decimal(12,2),
[5] decimal(12,2));
INSERT INTO #Locations([Location], [1], [2], [3], [4], [5]) values
('[a]', 10.00, Null, Null, 20.00, Null),
('[b]', Null, 30.00, Null, Null, Null);
if not exists (select 1 from #Locations where [3] is not null)
alter table #Locations
drop column [3];
select * from #Locations;
Location 1 2 4 5
[a] 10.00 NULL 20.00 NULL
[b] NULL 30.00 NULL NULL
As I understood ,to check the data that contain of values Null use this query like that:
SELECT 1 -- with using a literal
FROM (table)
HAVING COUNT(a) = 0
AND COUNT(*) > 0;
After that remove the columns with using this query :
Alter table <Table Name> drop column <Column Name>
Related
This question already has answers here:
SQLServer IDENTITY Column with text
(8 answers)
how to create auto increment column with characters and number like alphanumeric in sql server?
(2 answers)
Closed 6 months ago.
Let's say I have this table with the identity column pkid, how can I generate the cust_num as VIP000000 + <pkid> when inserting a record like this?
pkid
cust_name
cust_num
1
Tom
VIP0000001
2
May
VIP0000002
10
John
VIP0000010
CREATE TABLE [dbo].[tbl01]
(
[pkid] [numeric](9, 0) IDENTITY(1,1) NOT NULL,
[cust_name] [varchar](50) NOT NULL,
[cust_num] [varchar](20) NOT NULL
) ON [PRIMARY]
The easiest solution based on an IDENTITY column is to use a computed column - like this:
ALTER TABLE dbo.tbl01
ADD cust_num AS 'VIP' + RIGHT('000000' + CAST(pkid AS VARCHAR(6)), 6) PERSISTED;
Now, every time you insert a row into tbl01 without specifying values for pkid or cust_num:
INSERT INTO dbo.tbl01 (Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically increase your pkid value, and cust_num will contain values like VIP000001, VIP000002,...... and so on - automatically, safely, reliably, no duplicates.
UPDATE
Since you can't change your table definition, you will most likely need to use an AFTER INSERT trigger - something like this:
CREATE TRIGGER trgTbl01AddCustNum
AFTER INSERT
ON dbo.tbl01
AS
BEGIN
UPDATE tbl01
SET cust_num = 'VIP' + RIGHT('000000' + CAST(pkid AS VARCHAR(6)), 6)
FROM tbl01
INNER JOIN Inserted i ON i.pkid = tbl01.pkid;
END;
I have a table like this:
TableName
dates
ModelName
BaseUnitPerPallet
pallet
Calendar
June
Null
4
1
Country
June
Null
2
6
Product
June
DOWNSTREAM
Null
8
ProductBOM
June
DOWNSTREAM
9
9
and I want a table like this:
Columns
values
TableName
Calendar
TableName
Country
TableName
Product
TableName
ProductBOM
where columns field is the headers of the previous table, and values are the values in an unpivot way.
I have been trying without success the unpivot logic:
SELECT Columns, Values
FROM
(
SELECT TableName, dates, ModelName, BaseUnitPerPallet, pallet
FROM Database
as source_query
)
UNPIVOT
(
Values FOR Columns IN ( TableName, dates, ModelName, BaseUnitPerPallet, pallete)
)
as pivot_results
any advice or guidance would be great.
Additionally, any resource to do this dinamic? and apply the logic without write the column names?
Thanks in advanceĀ”
I'd recommend using APPLY to unpivot your table
Unpivot using APPLY
DROP TABLE IF EXISTS #YourTable
CREATE TABLE #YourTable (
ID INT IDENTITY(1,1) PRIMARY KEY
,TableName VARCHAR(100)
,Dates Varchar(25)
,ModelName VARCHAR(100)
,BaseUnitPerPallet TINYINT
,Pallet TINYINT
)
INSERT INTO #YourTable
VALUES
('Calendar','June',NULL,4,1)
,('Country','June',NULL,2,6)
,('Product','June','DOWNSTREAM',NULL,8)
,('ProductBOM','June','DOWNSTREAM',9,9)
SELECT A.ID,B.*
FROM #YourTable AS A
CROSS APPLY
(VALUES
('TableName',A.TableName)
,('Dates',A.Dates)
,('ModelName',A.ModelName)
,('BaseUnitPerPallet',CAST(A.BaseUnitPerPallet AS Varchar(100)))
,('Pallet',CAST(A.Pallet AS Varchar(100)))
) AS B(ColumnName,Val)
--WHERE B.Val IS NOT NULL /*Optional in case you want to ignore NULLs*/
ORDER BY A.ID,B.ColumnName
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Suppose I have this table with the index given below:
CREATE TABLE [dbo].[Jobs]
(
[Id] BIGINT NOT NULL PRIMARY KEY IDENTITY(1,1),
[Type] SMALLINT NOT NULL,
[Path] NVARCHAR(MAX),
[Name] VARCHAR(256),
)
GO
CREATE INDEX [IX_Jobs_Name_Type] ON [dbo].[Jobs] ([Name], [Type])
Which query will have better performance:
1.
UPDATE TOP((#JobCount + 3) / 4 )
Jobs WITH (ROWLOCK, READPAST)
SET [Name] = #NName
WHERE [Name] IS NULL AND (Type = 1 OR Type = 4)
UPDATE TOP((#JobCount + 3) / 8 )
Jobs WITH (ROWLOCK, READPAST)
SET [Name] = #NName
WHERE [Name] IS NULL AND Type = 1
UPDATE TOP((#JobCount + 3) / 8 )
Jobs WITH (ROWLOCK, READPAST)
SET [Name] = #NName
WHERE [Name] IS NULL AND Type = 4
Ignore in this case the correctness of the amount of rows updated,
Can doing a single search with 'or' for the Type be less effective than 2 separate queries because of the index?
You should of course try on your database, but the database should be able to apply the index in the OR case. It would be better written as:
WHERE [Name] IS NULL AND Type IN (1, 4)
I have a Three columns in the SQL table,
I want to show the sum of the total of two columns in the third column. How can I show that using SQL query.
This is my table structure
Id int Unchecked
Col_A int Unchecked
Col_B int Unchecked
Total int Checked
There is no need to store the total in the table, you can simply calculate it as part of your SQL query as follows:
SELECT
Id,
Col_A,
Col_B,
Col_A + Col_B AS Total
FROM tablename
You can use comuted column for this:
CREATE TABLE [dbo].[Test](
[a] [INT] NULL,
[b] [INT] NULL,
[c] AS ([a]+[b])
) ON [PRIMARY]
GO
INSERT INTO dbo.Test
( a, b )
VALUES ( 1, -- a - int
2 -- b - int
)
SELECT * FROM dbo.Test
Results:
a b c
1 2 3
Here is my table where the colums are salary and variable.
Now i need the sum of basic and variable as total.
Here is the query for that-
select basic,variable,(basic+variable) as total from salary
or if you just want to display total:
Try the following -
ALTER TABLE TABLENAME ADD colC AS ColA * ColB
Please Check this Sample Sql fiddle:http://www.sqlfiddle.com/#!3/f59ae.
In this way only i want output.first 2 columns Should contain values that can be anything
and rest columns should contain Hello values without considering Create Table statement.
I want to write a query that will insert 2 values into 2 columns and Hello into all other columns.
Suppose I have 100 columns then I want 10 and 20 values to be inserted into col1 and col2 and Hello into all other 98 columns.
Likewise if I have 200 columns then I want 10 and 20 values to be inserted into col1 and col2 and Hello into the other 198 columns.
I have written a query which but I thought it's a basic query so I am not writing here. So downvoters please consider that.
How to write this query???
You can do this by just adding the Default constraint to column's which you don't want to insert values explicitly. I hope #Manish Pant's answer should help you to do that.
Based on your comments you want do this only by using query. So you need to use Dynamic sql to do this.
Simple Demo
Schema
CREATE TABLE [dbo].[Test](
[id] [int] IDENTITY(1,1) NOT NULL,
[Country] [varchar](100) NULL,
[State] [varchar](100) NULL,
[City] [varchar](100) NULL,
[Population (in Millions)] [varchar](100) NULL
)
Declare a variable to hold the Dynamic sql
DECLARE #cl_val NVARCHAR(max)='Insert into Test('
Pull all the columns from sys.columns view and filter the identity column
SELECT #cl_val += Quotename(NAME) + ','
FROM sys.columns
WHERE Object_name(object_id) = 'Test'
AND is_identity <> 1
ORDER BY NAME
SELECT #cl_val = LEFT(#cl_val, Len(#cl_val)-1) + ') values (' -- Remove the trailing comma
Here add the values only to the column in case statement which you are explicitly passing value in else part add the default value
SELECT #cl_val += CASE
WHEN NAME ='City' THEN '''A'''
WHEN NAME='country' THEN '''c'''
ELSE '''Hello'''
END + ','
FROM sys.columns
WHERE Object_name(object_id) = 'Test'
AND is_identity <> 1
ORDER BY NAME
SELECT #cl_val = LEFT(#cl_val, Len(#cl_val)-1) + ')' -- Remove the trailing comma
--PRINT #cl_val
EXEC Sp_executesql #cl_val
select * from test
Result
id Country State City Population (in Millions)
-- ------- ----- ---- ------------------------
1 c Hello A Hello
If All other columns are set as Nullable then into your Insert statement you can write statement By without considering your Nullable fields.
Suppose for example your Table named Student with properties is:
Student ::
Name,
RollNo,
OptionalField_1,
OptionalField_2,
OptionalField_3
where columns with OptionalField are Nullble fields.
In this case you can write your Query simply as ::
INSERT INTO Student (Name,RollNo) VALUES ('MyName',12);
So this will make an ENtry with two column values & all remaining as Nullable.
For your better understandings you can refer :: http://www.w3schools.com/sql/sql_insert.asp
You can use this for your query:
create table mytable(
col1 varchar not null,
col2 varchar not null,
col3 varchar not null default 'Hello',
col4 varchar not null default 'Hello',
col5 varchar not null default 'Hello',
so on...... );
insert into mytable(col1,col2) values('10','20');