How to remove Header in csv file generated by sql command - sql

I am working on sql script for getting data from database to csv file,for that i created batch file.when i run batch file it genarated below table as a result
but with result is showing with some dummy data like "Changed database context to 'KMSSource'." and "(1 rows affected)". I want only table and not "Changed database context to 'KMSSource'." and "(1 rows affected)".
I'm using this code
Note:This is sql server query.
create TABLE TempTable
(
IBS_Total int,
IBS_Active int,
IBS_InActive int,
IBS_Only int,
KMS_Active int,
KMS_InActive int
)
INSERT INTO TempTable (IBS_Total,IBS_Active,IBS_InActive,IBS_Only,KMS_Active,KMS_InActive)
select (#IBS_Active+#IBS_INActive),#IBS_Active,#IBS_INActive,#KMS_DEVICENR,#KMS_Active,#KMS_OnlyTotal;
drop table #KMS_DEU
USE [KMSSource]
select * from TempTable
go
and I'm getting this result
**Changed database context to 'KMSSource'.**
IBS_Total IBS_Active IBS_InActive IBS_Only KMS_Active KMS_InActive
----------- ----------- ------------ ----------- ----------- ------------
41621 8632 32989 74 11916 3358
**(1 rows affected)**
BatchfileCode is :-->
#echo off
echo script executing....
:begin
sqlcmd -S%server% -b -i"Data\Report_IBS_KMS_KU_DUE.sql" -o"Extract\Report_IBS_KMS_KU_DUE.csv"
:end
Exit %ERRORLEVEL%

If you are getting an error when removing the USE statement, then you need to qualify the table names in the query, as below. Also be setting NO COUNT ON, you will get the message about rows affected.
SET NOCOUNT ON
CREATE TABLE KMSSource.dbo.TempTable
( IBS_Total INT, IBS_Active INT, IBS_InActive INT, IBS_Only INT, KMS_Active INT, KMS_InActive INT )
INSERT INTO KMSSource.dbo.#KMS_DEU
( IBS_Total, IBS_Active, IBS_InActive, IBS_Only, KMS_Active, KMS_InActive )
SELECT ( #IBS_Active + #IBS_INActive ), #IBS_Active, #IBS_INActive, #KMS_DEVICENR, #KMS_Active, #KMS_OnlyTotal;
DROP TABLE KMSSource.dbo.#KMS_DEU

Related

Why is this temporary table throwing an error about the number of column supplied?

I'm trying to run this specific code for a temp table, but somehow I get this error
Column name or number of supplied values does not match table definition
What's wrong?
DROP TABLE IF EXISTS #GamesDistribution
CREATE TABLE #GamesDistribution
(
Platform nvarchar(255),
Name nvarchar(255),
NA_Sales numeric,
EU_Sales numeric,
JP_Sales numeric
)
INSERT INTO #GamesDistribution
SELECT
properties.Platform,
properties.Name,
revenue.NA_Sales,
revenue.EU_Sales,
revenue.JP_Sales
FROM
games_properties AS Properties
JOIN
games_revenue AS Revenue ON properties.Game_ID = Revenue.Game_ID
--GROUP BY properties.platform
--ORDER BY Total_Games DESC, Total_NA_Sales DESC, Total_EU_Sales DESC, Total_JP_Sales DESC;
The problem here is that prior to you running your batch the table already exists. As such when the batch is parsed, by the compiler, the compilation fails; because the number of columns doesn't match that of the table already exists.
This can be replicated with the following:
CREATE TABLE #t (I int);
INSERT INTO #t (I)
VALUES(1);
GO
DROP TABLE IF EXISTS #t;
CREATE TABLE #t (I int, D date);
INSERT INTO #t
VALUES(2,GETDATE());
GO
SELECT *
FROM #t;
GO
DROP TABLE #t
db<>fiddle
This returns the error:
Msg 213, Level 16, State 1, Line 10
Column name or number of supplied values does not match table definition.
And the dataset:
I
1
This is because the 2nd batch, with the DROP TABLE IF EXISTS never ran; the compilation failed.
The "simple" solution here would be to put your DROP IF EXISTS in a separate batch, and also specify your columns:
DROP TABLE IF EXISTS #GamesDistribution;
GO
CREATE TABLE #GamesDistribution (Platform nvarchar(255),
Name nvarchar(255),
NA_Sales numeric, --Where is your precision and scale?
EU_Sales numeric, --Where is your precision and scale?
JP_Sales numeric); --Where is your precision and scale?
INSERT INTO #GamesDistribution (Platform,Name, NA_Sales,EU_Sales,JP_Sales)
SELECT properties.Platform,
properties.Name,
revenue.NA_Sales,
revenue.EU_Sales,
revenue.JP_Sales
FROM dbo.games_properties AS Properties
JOIN dbo.games_revenue AS Revenue ON properties.Game_ID = Revenue.Game_ID;
You can actually do this way
DROP TABLE IF EXISTS #GamesDistribution
SELECT properties.Platform,
properties.Name,
revenue.NA_Sales,
revenue.EU_Sales,
revenue.JP_Sales
INTO #GamesDistribution
FROM games_properties AS Properties
JOIN games_revenue AS Revenue
ON properties.Game_ID = Revenue.Game_ID
and then you can check the columns' data types of the temp table:
EXEC tempdb..sp_help '#GamesDistribution'
SELECT *
FROM tempdb.sys.columns
WHERE [object_id] = OBJECT_ID('tempdb..#GamesDistribution');
Note: It's always better to ensure the columns' data types. Your query might list different columns' data types.
Add GO statement under drop table as below.
DROP TABLE IF EXISTS #GamesDistribution
GO
CREATE TABLE #GamesDistribution
(
.
.
.

How do I create a variable/parameter that is a string of values in SQL SSMS that I can use as a substitute in my where clause?

This may be a very basic question, but I have been struggling with this.
I have a SSMS query that I'll be using multiple times for a large set of client Ids. Its quite cumbersome to have to amend the parameters in all the where clauses every time I want to run it.
For simplicity, I want to convert a query like the one below:
SELECT
ID,
Description
From TestDb
Where ID in ('1-234908','1-345678','1-12345')
to a query of the format below so that I only need to change my variable field once and it can be applied across my query:
USE TestDb
DECLARE #ixns NVARCHAR(100)
SET #ixns = '''1-234908'',''1-345678'',''1-12345'''
SELECT
ID,
Description
From TestDb
Where ID IN #ixns
However, the above format doesn't work. Can anyone help me on how I can use a varchar/string variable in my "where" clause for my query so that I can query multiple IDs at the same time and only have to adjust/set my variable once?
Thanks in advance :D
The most appropriate solution would be to use a table variable:
DECLARE #ixns TABLE (id NVARCHAR(100));
INSERT INTO #ixns(id) VALUES
('1-234908'),
('1-345678'),
('1-12345');
SELECT ID, Description
FROM TestDb
WHERE ID IN (SELECT id FROM #ixns);
You can load ids to temp table use that in where condition
USE TestDb
DECLARE #tmpIDs TABLE
(
id VARCHAR(50)
)
insert into #tmpIDs values ('1-234908')
insert into #tmpIDs values ('1-345678')
insert into #tmpIDs values ('1-12345')
SELECT
ID,
Description
From TestDb
Where ID IN (select id from #tmpIDs)
The most appropriate way is to create a table type because it is possible to pass this type as parameters.
1) Creating the table type with the ID column.
create type MyListID as table
(
Id int not null
)
go
2) Creating the procedure that receives this type as a parameter.
create procedure MyProcedure
(
#MyListID as MyListID readonly
)
as
select
column1,
column2
...
from
MyTable
where
Id in (select Id from #MyListID)
3) In this example you can see how to fill this type through your application ..: https://stackoverflow.com/a/25871046/8286724

SQL Server Management Studio - Query using text file

Let's say I have a text file that has the following lines
102
333
534
Then, in my SQL table, I have a few different columns:
AutoID | Name | Description
--------------------------------------
102  | Jackson  | [Description Here]
241  | Edward   | [Description Here]
333  | Timothy  | [Description Here]
437  | Nikky    | [Description Here]
534  | Jeremy   | [Description Here]
Is there anyway I can parse the text file through SQL Server Management Studio so that it will query the table and pull out every row that has a column (AutoID, in this case) that matches a line in the text file (Note, I only want the rows from a table that I would specify)?
This way I could edit them or update the rows that only match IDs in the text file.
The rows displayed in management studio would look like this.
 AutoID | NAME  | Description
--------------------------------------
102  | Jackson  | [Description Here]
333  | Timothy  | [Description Here]
534  | Jeremy   | [Description Here]
--What you need to do is import the text file into a table in your SQL database, and then compare its values to the table you want to query (which I have called AutoIDTest in my example).
--Using your example data, I've put together the following code that accomplishes this process.
--1. I created a destination table for the text file's values called TextImport. I've called the test text file E:\TestData.txt. Additionally, I'm assuming this text file only has one column, autoID.
--2. Then, I imported the data into the destination table using the BULK INSERT statement.
--3. Finally, I compared the data in TextImport to the table from which you are seeking values using an INNER JOIN statement.
CREATE TABLE AutoIDTest ---Create test table. Since your first column doesn't have a name, I'm calling it ID. I'm assuming AutoID and ID are both of type int.
(
ID int,
AutoID int,
Name varchar(25),
Description varchar(50)
)
INSERT INTO AutoIDTest -- Populate test table
VALUES
( 1, 102, 'Jackson', 'Description1'),
( 2, 241, 'Edward', 'Description2'),
( 3, 333, 'Timothy', 'Description3'),
( 4, 437, 'Nikky', 'Description4'),
( 5, 534, 'Jeremy', 'Description5')
CREATE TABLE TextImport --Create destination table for text file.
(
AutoID varchar(20),
)
BULK INSERT TextImport --Load Data from text file into TextImport table
FROM 'E:\TestData.txt' ---The name and location of my test text file.
WITH
(
ROWTERMINATOR ='\n'
);
SELECT ---Produce Output Data
ID,
t1.AutoID,
Name,
Description
FROM
AutoIDTest AS t1
INNER JOIN
TextImport AS t2
ON t1.autoID = cast(t2.autoID AS int) --convert varchar to int
OUTPUT
-- ID AutoID Name Description
-- --------- ----------- ------------------------- -------------------
-- 1 102 Jackson Description1
-- 3 333 Timothy Description3
-- 5 534 Jeremy Description5

While inserting data to two tables using stored procedure I am getting a mismatch error

I have a table called CompanyMaster_tbl with a table structure as follows.
Cid CompanyName Deleted
and another table named DepartmentMaster_tbl,with a table structure as follows.
dtld dtname dtphone dtemail cid deleted
I've written a stored procedure for inserting data into these tables as follows.
CREATE PROCEDURE [dbo].[InsertDetails](
#companyName varchar(150),
#dname varchar(150),
#dphon varchar(150),
#deleted int,
#cid int OUTPUT
) AS
BEGIN
INSERT INTO [dbo].CompanyMaster_tbl
VALUES (#companyName)
select #cid=cid
from [dbo].CompanyMaster_tbl
WHERE ##ROWCOUNT > 0 AND cid = scope_identity()
insert into DepartmentMaster_tbl
values(#dname,
#dphon)
end
When I execute this SP, i am getting error like this:
Column name or number of supplied values does not match table definition.
try this , mention coloumn name
INSERT INTO [dbo].CompanyMaster_tbl (CompanyName )
VALUES (#companyName)
INSERT into DepartmentMaster_tbl (dname,dphon)
values(#dname, #dphon)
You are giving wrong number of values to the table i.e. you have two columns in table CompanyMaster_tbl(i think your cid is identity(auto generated) there fore i did not mention it) but you can give only one value to the table, and same thing applies for DepartmentMaster_tbl. if you can't give the values to the table then mention column names in the insert statement otherwise give all column value
e.g.
Insert into CompanyMaster_tbl(CompanyName) values(#companyName)
or
Insert into CompanyMaster_tbl values(#companyName, #deleted)

How to create Temporary table with Dynamic query in SQL Server 2005

I want to create Temporary table dynamically in SQL Server 2005 like below.
Create Table ##EmpMonthlyTimeReport
(
EmpID UNIQUEIDENTIFIER,
EmpName VARCHAR(100),
TaskId UNIQUEIDENTIFIER,
[07 Nov] NVARCHAR(10),
[08 Nov] NVARCHAR(10),
[09 Nov] NVARCHAR(10)
)
In the above ##EmpMonthlyTimeReport table, columns [07 Nov], [08 Nov], [09 Nov] are NOT static. They are creating dynamically through another function.
Hence, I am dynamically constructing the above table in one variable called #EmpMonthlyTimeReport and I'm executing the constructed sql string like below:
EXEC(#EmpMonthlyTimeReport)
I am getting the following error:
Msg 50000, Level 16, State 1, Procedure SVS_WorkOnWeekends, Line 157
The name 'INSERT INTO ##EmpMonthlyTimeReport(EmpID, EmpName, TaskId)
SELECT EmpId, EmpName, TaskId FROM TableData
SELECT * FROM ##EmpMonthlyTimeReport
DROP TABLE ##EmpMonthlyTimeReport' is not a valid identifier.
Very silly work around.
I have changed the #EmpMonthlyTimeReport variable declaration from VARCHAR(MAX) to NVARCHAR(MAX)
That's it. Everything is working as expected.