Showing posts with label tsql. Show all posts
Showing posts with label tsql. Show all posts

Wednesday, 9 December 2020

Export CSV file from SQL Server from script.

 This is a quick way to export a SQL  View or Table to a CSV file

The file can only be exported to a folder on the local SQL Server where it has run.

First all you data must be in one view or table. I use a Temp table to do the Job.

Once you have your data in one place:-


Declare @sql as varchar(8000). @outputpath  as varchar(3000)

set @outputpath  ='c:\temp\testcsv.csv'

select @sql = 'bcp "select  * from Yourdb..Temptable " queryout ' + @outputpath + ' -c -t, -T -S '  + @@servername 

exec master..xp_cmdshell @sql

 EXECUTE AS login = 'user'

and there you have it, the @sql needs to be a large Varchar for this to run or it fails. @otputpath need to be on  the local sql server



Monday, 1 April 2019

Convert Kilometers to Miles in TQSL




To convert Kilometeres to Miles in Tsql Try this

CAST(ISNULL(tblManifestos.km, 0) * 0.62137 AS decimal)

Multipy the kilometers by 0.62137

The to round it to the nerest mile cast as a decimal



Tuesday, 29 January 2019

How To Get The Time Portion from Getdates





To get the date portion only from get dates try the following 



select CONVERT(VARCHAR(5),GETDATE(),114)   

this can then be used to see if  a time has passed


CONVERT(VARCHAR(5),GETDATE(),114)>'15:00' 

Monday, 19 March 2018

Data encrytion code VB,net Tsql


Found this knocking around the next and it works well if you need some encryption.
Create the following function in tsql


 
/****** Object: UserDefinedFunction [dbo].[fnEncDecRc4] Script Date: 03/19/2018 12:31:40 ******/

SET ANSI_NULLS ON


GO
SET QUOTED_IDENTIFIER ON


GO
ALTER FUNCTION [dbo].[fnEncDecRc4]


(
@Pwd VARCHAR(256),

@Text VARCHAR(8000)


)
RETURNS VARCHAR(8000)


AS

BEGIN
DECLARE @Box TABLE (i TINYINT, v TINYINT)

INSERT @Box

(

i,

v

)

SELECT i,

v

FROM dbo.fnInitRc4(@Pwd)

DECLARE @Index SMALLINT,

@i SMALLINT,

@j SMALLINT,

@t TINYINT,

@k SMALLINT,

@CipherBy TINYINT,

@Cipher VARCHAR(8000)

SELECT @Index = 1,

@i = 0,

@j = 0,

@Cipher = ''

WHILE @Index <= DATALENGTH(@Text)

BEGIN

SELECT @i = (@i + 1) % 256

SELECT @j = (@j + b.v) % 256

FROM @Box b

WHERE b.i = @i

SELECT @t = v

FROM @Box

WHERE i = @i

UPDATE b

SET b.v = (SELECT w.v FROM @Box w WHERE w.i = @j)

FROM @Box b

WHERE b.i = @i

UPDATE @Box

SET v = @t

WHERE i = @j

SELECT @k = v

FROM @Box

WHERE i = @i

SELECT @k = (@k + v) % 256

FROM @Box

WHERE i = @j

SELECT @k = v

FROM @Box

WHERE i = @k

SELECT @CipherBy = ASCII(SUBSTRING(@Text, @Index, 1)) ^ @k,

@Cipher = @Cipher + CHAR(@CipherBy)

SELECT @Index = @Index +1

END

RETURN @Cipher


END


Then use the following to call it this is VB.net.
first call sets the encryption

select database name.dbo.fnEncDecRc4('encryption key','OrderID')



second call decodes.
select database name.dbo.fnEncDecRc4('encryption key','OrderID')

I have used this to encrypt passwords in tables  and to pass query parameters in the address bar  of web pages.





 

Monday, 20 February 2017

Restart SQL Server mail system









To restart SQL Mail run the following

first stp it running
EXECUTE dbo.sysmail_stop_sp

no start it again.
EXECUTE  sysmail_start_sp

This works fine i find.

Thursday, 16 February 2017

Export Select Query To Delimited File




Image result for sql



The following code  will output the results of the query  (select * from  logic..temp1) to a CSV file

Please be aware that the output path will be to the sql machine if you use c:\.  Use \\servername\folder\filename.extention  to output the file to another machine.




declare @outputpath varchar(800) ----------Varchar(max) is not allowed
declare @sql varchar(8000)


set @outputpath = '\\SERVER\Shared_Drive\nick.csv'   --------- Set the Path


select @sql = 'bcp "select * from  logic..temp1"  queryout ' + @outputpath + ' -c -t, -T -S'  + @@servername

print @sql

exec master..xp_cmdshell @sql



the file will then appear in the appropriate folder.
To change the delimiter change the yellow Highlighted Character. for a pipe you will have to replace it with ^|  so the line looks like this ' -c -t^| -T -S'

Monday, 23 January 2017

Round Up To Next Whole Number TSQL



Image result for round up numbers


I was looking for a way to round up the results of a query to the next whole number and after
 fair bit of searching the net and experimenting to get this to work in SQL 2005
The result was


declare @totalpallets as int
declare @total as int
declare @palletsize as int


set total_pallets =  (select ceiling(cast(@total as float)/cast(@palletsize as float)))



This does the job admirably

Monday, 11 May 2015

Create a Delimited List in TSQL


The Following code uses Stuff to generate a delimited list from a postcode table using TSQL

SELECT STUFF((SELECT ','+ char(39) + [postcode]+char(39)
 FROM tblPostcodeRoute  where carrier = 16
 ORDER BY [postcode]
 FOR XML PATH('')), 1, 1, '') AS [Output]

Result

'HS1','HS2','HS3','HS4','HS5','HS6','HS7','HS8','HS9','IV10','IV11','IV14','IV15','IV16','IV17','IV18','IV19','IV20','IV21','IV22','IV23','IV24','IV25','IV26','IV27','IV28','IV4','IV40','IV41','IV42','IV43','IV44','IV45','IV46','IV47','IV48','IV49','IV5','IV51','IV52','IV53','IV54','IV6','IV63','IV7','IV8','IV9','KA27','KA28','KA29','KW1','KW10','KW11','KW12','KW13','KW14','KW15','KW16','KW17','KW2','KW3','KW4','KW5','KW6','KW7','KW8','KW9','PA20','PA23','PA24','PA25','PA26','PA27','PA28','PA29','PA31','PA32','PA33','PA34','PA37','PA38','PA41','PA42','PA43','PA44','PA45','PA46','PA47','PA48','PA49','PA60','PA61','PA62','PA63','PA64','PA65','PA66','PA67','PA68','PA69','PA70','PA71','PA72','PA73','PA74','PA75','PA76','PA77','PA78','PA80','PH20','PH21','PH22','PH23','PH24','PH25','PH26','PH30','PH31','PH32','PH33','PH34','PH35','PH36','PH37','PH38','PH39','PH40','PH41','PH42','PH43','PH44','PH49','PH50','ZE1','ZE2','ZE3'

Tuesday, 21 April 2015

ADD Users to SQL via TSQL Script

I had need to create adhoc users with an SQL login so I did some digging and put together this TSQL



GO
declare @username as varchar(50)
set @username ='test1'
DECLARE @SQL NVARCHAR(4000);
begin

SET @SQL = 'CREATE LOGIN ' + @username + ' WITH PASSWORD = ''12345'', DEFAULT_DATABASE=[Logic], DEFAULT_LANGUAGE=[British], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF';
EXECUTE(@SQL);

end

use {Your DB Name}
EXEC sp_grantdbaccess @username
EXEC SP_ADDROLEMEMBER N'db_datareader', @username;
        EXEC SP_ADDROLEMEMBER N'db_datawriter', @username;


The script can be put into a procedure and passing the username to it will create a user with read \right privileges on the DB.

Monday, 19 January 2015

Get data in current week

Get  data for the current week in TSQL

The below is how to get the sum of something for a week

select sum(somthing) from atable  WHERE your_date  >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) / 7 * 7, 0)
AND  your_date  <= DATEADD(DAY, DATEDIFF(DAY, -1, GETDATE()), 0)






You could also use

select* from atable  WHERE your_date  >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) / 7 * 7, 0)
AND  your_date  <= DATEADD(DAY, DATEDIFF(DAY, -1, GETDATE()), 0)


to get all data for that week

Tuesday, 25 November 2014

Stored procedure skips date




If you are using date math in a stored procedure  like   datepart(dw,getdate())  which returns a  2 for Tuesday  make sure you set the Datefirst parameter to the first day of the week for the country you are in. set  DATEFIRST 1.  see here

Failure to do this could result in your date calculations not running properly, Tuesday may become 3. This is due to the fact that when run manually the calculation are run differently than when a Job is run from SQL server agent.







Wednesday, 19 November 2014

Can not alter table tsql




If you find the following does not work

Alter table Table_name modify COLUMN  column_name  varchar(101);

Then try

Alter table Table_name Alter COLUMN  column_name  varchar(101);

This works on sql server 2005


Related
 
Cannot Alter Table Being Used For Replication


Monday, 10 November 2014

Convert Column results to delimited string in TSQL


Use the below to convert the results of a query from this
123
125
156
254
214
To
123,125,156,254,214



DECLARE @result varchar(1000)

SET @result = ''

SELECT @result = @result + cast(order_id as varchar) + ',' FROM tblorders WHERE tblstatus = 2

select substring(@result, 0, len(@result))

This has worked for me no problems you can change the delimiter by changing the ' ,'



Original code that this was based on can be  found here




Thursday, 30 October 2014

Check if a temporary table exist in as stored procedure


To check if a temporary table exist  in as stored procedure use the following

 if object_id(N'tempdb..#temp') is not null

Where #temp is your table

Then do something

if object_id(N'tempdb..#temp') is not null
 drop table #temp

Friday, 30 May 2014

Date intervals for VB and Tsql

Date intervals for Sql Server



year yy, yyyy
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw
hour hh
minute mi, n
second ss, s
millisecond ms

Usage  DATEPART(datepart,date)


Dates for Visual Basic

DateInterval.Day d Day of month (1 through 31)
DateInterval.DayOfYear y Day of year (1 through 366)
DateInterval.Hour h Hour
DateInterval.Minute n Minute
DateInterval.Month m Month
DateInterval.Quarter q Quarter
DateInterval.Second s Second
DateInterval.Weekday w Day of week (1 through 7)
DateInterval.WeekOfYear ww Week of year (1 through 53)
DateInterval.Year yyyy Year
Usage DatePart(DateInterval.Quarter, ActualDate)

Tuesday, 25 June 2013

Insert Row with Identity


To insert values with a specific id use the following code this will insert a line of data with a defined id.

Beware whilst this is running NO AUTO IDENT WILL WORK keep every one away from this table.

SET IDENTITY_INSERT Table name ON

 INSERT table name (UID, Value) VALUES (2006, 'any value')

 SET IDENTITY_INSERT Table name OFF


If this fails due to a syntax error in the insert statement then  the Identity will remain OFF


Multi Point USB Charger

  USB Plug Charger, 4-Port USB Fast Charger Plug with 33W Intelligent Quick Charge 3.0 Wall Charger, Multi USBPower Adapter UK Fast Charging...