BCP Export Data convert - sql-server-bcp

ALTER PROCEDURE [dbo].[sp_helptext3]
(#ProcName VARCHAR(256))
AS
SET NOCOUNT ON
BEGIN
DECLARE #path VARCHAR(MAX)
DECLARE #filepath_loction VARCHAR(MAX)
SET #filepath_loction = '\\SOLVERLAPT292\tempfolder\new.txt'
EXEC #path = sp_helptext2 #ProcName
SET #filepath_loction = #path
SET #sql = 'bcp "' + #sql + '" queryout "' + #filename +'" -c -r"''\n"
-t"'',''" -S '+##servername+' -T'
SELECT #filepath_loction
END
Output I got it because not convert into text file format I get this error:
Msg 214, Level 16, State 201, Procedure xp_cmdshell, Line 1
Procedure expects parameter 'command_string' of type 'varchar'.

Related

Error on INSERT INTO SELECT in query hosted on variable

I'm a little bit conffused.
Can anyone tell me why i get sintaxis error on the next script?
declare #schema1 NVARCHAR(100)
set #schema1 = 'ex.:DATABASENAME'
declare #query NVARCHAR(500)
set #query = 'INSERT UsersSessions (UserSessionId, IpAddress, ChannelId, IsEmployee, UserId, ClientFullName, UserAgent, StartDate, ExpirationDate, SessionDuration)
SELECT us.UserSessionId, us.IpAddress, us.ChannelId, CASE WHEN us.ChannelId = 2 THEN 1 ELSE 0 END AS IsEmployee, us.UserId, (u.Name + u.LastName) as ClientFullName, us.UserAgent, us.StartDate, us.ExpirationDate, (us.ExpirationDate-us.StartDate) AS SessionDuration
FROM ' + #schema1 + '.UsersSessions us INNER JOIN ' + #schema1 + '.Users u ON us.UserId = u.UserId WHERE us.UserSessionId NOT IN (SELECT UserSessionId FROM UsersSessions)'
EXEC(#query)
RESULT:
Msg 156, Level 15, State 1, Line 15
Incorrect syntax near the keyword 'Use'.
Completion time: 2021-11-16T11:10:32.6309920-03:00
If i remove the Insert block, i get the script running
declare #schema1 NVARCHAR(100)
set #schema1 = 'ex.:DATABASENAME'
declare #query NVARCHAR(500)
set #query = '
SELECT us.UserSessionId, us.IpAddress, us.ChannelId, CASE WHEN us.ChannelId = 2 THEN 1 ELSE 0 END AS IsEmployee, us.UserId, (u.Name + u.LastName) as ClientFullName, us.UserAgent, us.StartDate, us.ExpirationDate, (us.ExpirationDate-us.StartDate) AS SessionDuration
FROM ' + #schema1 + '.UsersSessions us INNER JOIN ' + #schema1 + '.Users u ON us.UserId = u.UserId WHERE us.UserSessionId NOT IN (SELECT UserSessionId FROM UsersSessions)'
EXEC(#query)
RESULT:
(1 row affected)
Completion time: 2021-11-16T11:11:07.6741062-03:00
I think some char is missing?
Thanks and regards!
Your query variable length is not sufficient, modify it as below. Also, schema name can accept only certain characters, colon is not allowed I guess.
declare #query NVARCHAR(max)

FakeFunction Results based on Test

I'm using tSqlt to unit test a stored procedure. This stored proc joins to a table-valued function, the function takes no parameters and the results are filtered via the join on clause.
I'm writing multiple tests for the stored proc. Is there a way to to fake the function in such a way that I could return different results based on the test that is being run.
The only solution I can think of is to create a fake per test, which is possible but a little more than clunky.
I imagine an ideal solution would be some sort of variable exposed in tsqlt that would allow me to determine which test I'm in and use some sort of case statement or something.
I use following procedure for that. It is not ideal, but working:
CREATE PROCEDURE [tSQLt].[FakeFunction2]
#FunctionName VARCHAR(200)
, #SchemaName VARCHAR(200) = 'dbo'
, #tmpTableName VARCHAR(200)
AS
BEGIN
DECLARE #Params VARCHAR(2000);
DECLARE #NewName VARCHAR(MAX) = #FunctionName + REPLACE(CAST(NEWID() AS VARCHAR(100)), '-', '');
DECLARE #FunctionNameWithSchema VARCHAR(MAX) = #SchemaName + '.' + #FunctionName;
DECLARE #RenameCmd VARCHAR(MAX) = 'EXEC sp_rename ''' + #FunctionNameWithSchema + ''', ''' + #NewName + ''';';
DECLARE #newTbleName VARCHAR(200) = #SchemaName + '.tmp' + REPLACE(CAST(NEWID() AS VARCHAR(100)), '-', '');
DECLARE #newTblStmt VARCHAR(2000) = 'SELECT * INTO ' + #newTbleName + ' FROM ' + #tmpTableName;
EXEC tSQLt.SuppressOutput #command = #newTblStmt;
SELECT #Params = p.params
FROM
( SELECT DISTINCT ( SELECT p1.name + ' ' + type1.name + b.brk + ',' AS [text()]
FROM sys.types type1
JOIN sys.parameters p1 ON p1.system_type_id = type1.system_type_id
CROSS APPLY
( SELECT CASE WHEN type1.name LIKE '%char' OR type1.name = 'varbinary' THEN
REPLACE(
'(' + CAST(p1.max_length AS VARCHAR(5)) + ')', '-1', 'MAX')
WHEN type1.name IN ('decimal', 'numeric') THEN
'(' + CAST(p1.precision AS VARCHAR(5)) + ', '
+ CAST(p1.scale AS VARCHAR(5)) + ')'
WHEN type1.name IN ('datetime2') THEN
'(' + CAST(p1.scale AS VARCHAR(5)) + ')'
ELSE ''
END AS brk) b
WHERE p1.object_id = p.object_id
ORDER BY p1.parameter_id
FOR XML PATH('')) [parameters]
FROM sys.objects AS o
LEFT JOIN sys.parameters AS p ON p.object_id = o.object_id
LEFT JOIN sys.types AS t ON t.system_type_id = p.system_type_id
WHERE o.name = #FunctionName AND o.schema_id = SCHEMA_ID(#SchemaName)) [Main]
CROSS APPLY
(SELECT LEFT(Main.[parameters], LEN(Main.[parameters]) - 1) params) AS p;
EXEC tSQLt.SuppressOutput #command = #RenameCmd;
DECLARE #newFunctionStmt VARCHAR(MAX) = '';
SET #newFunctionStmt = 'CREATE FUNCTION [' + #SchemaName + '].[' + #FunctionName + '](' + COALESCE(#Params,'') + ')';
SET #newFunctionStmt = #newFunctionStmt + ' RETURNS TABLE AS RETURN (SELECT * FROM ' + #newTbleName + ');';
EXEC tSQLt.SuppressOutput #command = #newFunctionStmt;
END;
and usage:
INSERT INTO #table
(col1
, col2
, col3)
VALUES
('a', 'b', 'c'),
('d', 'e', 'f');
EXEC tSQLt.FakeFunction2 #FunctionName = 'function_name'
, #SchemaName = 'dbo'
, #tmpTableName = '#table';
now with any passed parameter to that function it will always return the values from #table temp table
I thought of one potential solution.
I create a table within the test class schema and populate it with the results I wish to be returned per test.
CREATE TABLE testcalass.fakefunction_Results
(
ID INT,
Value NUMERIC(12, 5)
)
GO
CREATE FUNCTION testcalass.fakefunction()
RETURNS #results TABLE
(
ID INT,
Value NUMERIC(12, 5)
)
BEGIN
INSERT INTO #results
SELECT ID, Value FROM testcalass.fakefunction_Results
END
GO
So basically, I can populate is functions results at the top of my tests during the assemble section.

sql create table with stored procedure with optional parameters

I am writing a report based on parameters, utilizing a sql stored procedure. Problem is there are several 'optional' parameters, where the user can choose a value, or ignore that parameter altogether. I need to use the stored proc as a dataset in asp.net report. Only way I thought of doing it is to create a table from the results. But I'm clueless.
How do I turn this into a 'create table' stored proc?
Any assistance is greatly appreciated.
Cindy
This is what I have so far -
ALTER PROCEDURE [dbo].[rspSCL]
-- Add the parameters for the stored procedure here
(#year as int,
#RRID as int,
#State as nchar(2),
#Sub as varchar(75),
#app as int,
#sprayed as int,
#subcontracted as int,
#thirdapp as bit)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
DECLARE #SQL as varchar(4000)
DECLARE #SUBQ AS varchar(400)
--what fields need to be seen
SET #SQL = 'SELECT C.CRID, C.DOT, C.RR, C.Pref, C.MP, C.Division, C.Subdivision,C.City, C.Street,
C.State, C.County, C.RestrictedCounty, C.Remarks, C.SpecialInstructions, C.Route, C.ThirdAppRequired,
C.MainTrks, C.OtherTrks, C.OnSpur, C.MaxSpeed, C.SubContracted, C.FenceEncroachment, C.Lat, C.Long,
C.PropertyType, C.WarningDevice,C.Surface, C.ROWNE, C.ROWNW, C.ROWSE, C.ROWSW, C.ROWWidth, C.ExtNE,
C.ExtNW, C.ExtSE, C.ExtSW, C.TempActive, A.Spray, A.ContractYear'
SET #SUBQ =
CASE WHEN #app = 1 THEN
'FROM Crossings LEFT OUTER JOIN
(select A.CRID, A.spray FROM ApplicationData A
WHERE A.ContractYear = ' + CAST( #year AS varchar(4)) + ') as APPS
ON Crossings.CRID = APPS.CRID'
WHEN #app = 2 THEN
'FROM Crossings inner join
(SELECT crid, C,OUNT(APPID)as count
from ApplicationData
where ContractYear = ' + CAST( #year AS varchar(4)) + '
group by CRID) as APPS
ON Crossings.CRID = APPS.CRID
WHERE Crossings.RR = '+ CAST( #RRID AS varchar(4)) + '
and crossings.state = '+ #state + '
and count = 1'
when #app = 3 THEN
'FROM Crossings inner join
(SELECT crid, COUNT(APPID)as count
from ApplicationData
where ContractYear = ' + CAST( #year AS varchar(4)) + '
group by CRID) as APPS
ON Crossings.CRID = APPS.CRID
WHERE Crossings.RR = '+ CAST( #RRID AS varchar(4)) + '
and crossings.state = '+ #state + '
and count = 2'
ELSE ''
END
--add the FROM to the query
SET #SQL = #SQL + #SUBQ
--add the subdivision to the where statement
If #Sub != 'ALL'
SET #SQL = #SQL + 'AND (C.Subdivision = ' + #Sub + ')'
ELSE
SET #SQL = #SQL
--add sprayed to where
DECLARE #S as varchar(100)
SET #S =
CASE WHEN #sprayed = 1 THEN
'AND (A.sprayed = 1)'
WHEN #sprayed = 0 THEN
'AND (A.sprayed = 0)'
ELSE
''
END
SET #SQL = #SQL + #S
--add subcontracted to where
DECLARE #C as varchar (100)
SET #C =
CASE WHEN #subcontracted = 0 THEN
'AND (C.subcontracted = 0)'
WHEN #subcontracted = 1 THEN
'AND (C.subcontracted = 1)'
ELSE
''
END
SET #SQL = #SQL + #C
IF #thirdapp = 1
SET #SQL = #SQL + 'AND (C.ThirdAppRequired = 1)'
ELSE
SET #SQL = #SQL
END

Operand data type varchar is invalid for sum operator - Procedure Error Correction

I am using SQL Server - 2005...
ALTER Proc [dbo].[ExamResult] (#Course_Id varchar(100), #Semester varchar(10))
as
begin
declare #subjname varchar(100)
declare #subjects varchar(7000)
declare #subjectsselection varchar(7000)
declare #SumSelection varchar(7000)
declare #NoOfSubjects int
set #NoOfSubjects = 0
set #subjects = ''
set #subjectsselection = ''
set #SumSelection = ''
DECLARE subject_cursor CURSOR
FOR SELECT distinct Subject_Name FROM Exam_Result where course_id = #Course_Id And Semester = #Semester
OPEN subject_cursor
FETCH NEXT FROM subject_cursor
INTO #subjname
WHILE ##FETCH_STATUS = 0
BEGIN
set #subjects = #subjects + '[' + #subjname + '],'
set #subjectsselection = #subjectsselection + 'Sum(Isnull([' + #subjname + '],0)) As [' + #subjname + '],'
set #SumSelection = #SumSelection + 'Sum(Isnull([' + #subjname + '],0))+'
set #NoOfSubjects = #NoOfSubjects + 1
FETCH NEXT FROM subject_cursor
INTO #subjname
End
CLOSE subject_cursor;
DEALLOCATE subject_cursor;
select #subjects = LEFT(#subjects, LEN(#subjects) - 1)
select #subjectsselection = LEFT(#subjectsselection, LEN(#subjectsselection) - 1)
select #SumSelection = LEFT(#SumSelection, LEN(#SumSelection) - 1)
print #subjects
print #subjectsselection
print #SumSelection
declare #query nvarchar(4000)
set #query = 'select S.Enroll_Number, pvt.Student_Name, pvt.Course_Id, pvt.Semester, ' + #subjectsselection + ','
set #query = #query + 'Exam_Type,' + #SumSelection + ' As Grand_Total, '
set #query = #query + '(' + #SumSelection + ')' + '/' + convert(varchar(10),#NoOfSubjects) + ' As Avg'
set #query = #query + ' From '
set #query = #query + '(select Enroll_Number, Student_Name, Course_Id, Semester, Subject_Name, MarksObtained, Exam_Type from Exam_Result ) ps '
set #query = #query + ' pivot(sum(MarksObtained) for Subject_Name in (' + #subjects + ')) as pvt'
set #query = #query + ' inner join Stud_Info S on S.Enroll_Number = pvt.Enroll_Number '
set #query = #query + ' where pvt.Course_Id = ''' + #Course_Id + ''' and pvt.Semester = ''' + #Semester + ''''
set #query = #query + ' group by S.Enroll_Number, pvt.Student_Name, pvt.Course_Id, pvt.Semester, Exam_Type'
print #query
exec sp_executesql #query
end
Exam_Result table:
CREATE TABLE [dbo].[Exam_Result](
[Result_Id] [int] IDENTITY(1,1) NOT NULL,
[Enroll_Number] [varchar](50) NULL,
[Student_Name] [varchar](100) NULL,
[Course_Id] [varchar](50) NULL,
[Semester] [varchar](50) NULL,
[Subject_Id] [varchar](50) NULL,
[Subject_Name] [varchar](50) NULL,
[MarksObtained] [Varchar](10) NULL,
[Exam_Type] [varchar](50) NULL)
Sample data query...
INSERT into Exam_Result VALUES('11147','Mr.Mack28','CIV','1','PS1','ps1','60','Final')
INSERT into Exam_Result VALUES('11147','Mr.Mack28','CIV','3','PS1','ps1','70','Final')
INSERT into Exam_Result VALUES('11147','Mr.Mack28','CIV','3','PS1','ps1','80','Final')
INSERT into Exam_Result VALUES('11147','Mr.Mack28','CIV','3','PS1','ps1','20','Internal')
INSERT into Exam_Result VALUES('11147','Mr.Mack28','CIV','3','PS1','ps1','22','Internal')
Student_Info table: I just use for retrieved Student_Information like Enroll_Number...
CREATE TABLE [dbo].[Stud_Info](
[Enroll_Number] [varchar](20) NOT NULL,
[Student_Name] [varchar](20) NULL,
[Course_Type] [varchar](20) NULL,
[Course_Id] [varchar](20) NULL,
[Semester] [varchar](20) NULL,
[Password] [varchar](20) NULL,
[Gender] [varchar](6) NULL,
[City] [varchar](15) NULL,
[Mobile_Number] [varchar](10) NULL)
It gives me error like this...
Msg 8117, Level 16, State 1, Line 1
Operand data type varchar is invalid for sum operator.
Rahul: as per you answer I updated like this but it still gives error......
set #query = #query + ' pivot(sum(cast(MarksObtained as int)) for Subject_Name in (' + #subjects + ')) as pvt'
I think it gives error because I am using the MarksObtained column (as varchar(10))...plz give me a suggestion how I can convert varchar to int so that summation of total MarksObtained can be done.
You can convert like this way:
SUM (CONVERT(int,<your varchar column>))
This will work if your varchar column actually holds numeric value. Otherwise, you can try casting it using cast function like:
sum(cast(varchar_column as int))
EDIT:
Created a sample table with just 2 column (name and marksobtained), both of type varchar(10) and inserted some data to it. So that my select * looks like
name marksobtained
Mr. Anil 30
Mr. sunil 70
Mr. patel 70
Summed the marks like
select SUM(cast(marksobtained as int)) as 'totalmarksobtained' from sampletab
Which returned 170.
What values does #subjects have? Post some sample.
you can use "cast" in your query
example:
select sum(cast(Enter_your_field_name as int)) from Table_name
Hope it works for you.

Paging in my web page

I have a large data set and i have to apply paging on that data set and after that the result set should be another data set. What is the reliable method to achieve that.
I have tried with 'PagedDataSource' class but i don't know how it is possible to convert to dataset or data table.
In my case i need a general solution. I have to bind to a control like gridview as well as i have to used it with normal html table.
check this article doing same thing you want : http://www.codeproject.com/KB/custom-controls/EnhanceGrid.aspx
following sp returns record that you want
CREATE PROCEDURE [dbo].[GetRequestedRecordByPage]
#FromList nvarchar(200) -- Table Name
,#SortingCol nvarchar(200) -- Sorting column Name
,#SelectList nvarchar(200) = '*' -- Select columns list
,#WhereClause nvarchar(200) = '' -- Where clause i.e condition
,#PageNum int = 1 -- Requested page number
,#PageSize int = 5 -- No of record in page
,#TotalNoOfRecord int output -- Total no of selected records
AS
Begin
SET NOCOUNT ON
DECLARE #Query nvarchar(max) -- query going to be execute
IF rtrim(ltrim(#WhereClause)) <> ''
BEGIN
SET #Query ='SELECT #TotalNoOfRecord = COUNT(*)
FROM ' + #FromList + '
WHERE ' + #WhereClause
END
ELSE
BEGIN
SET #Query ='SELECT #TotalNoOfRecord = COUNT(*)
FROM ' + #FromList
END
/* Count no. of record */
EXEC sp_executeSQL
#Query,
#params = N'#TotalNoOfRecord INT OUTPUT',
= #TotalNoOfRecord OUTPUT
DECLARE #lbound int, #ubound int
/* Calculating upper and lower bound */
SET #lbound = ((#PageNum - 1) * #PageSize)
SET #ubound = #lbound + #PageSize + 1
/* Get list of record(s) */
SELECT #Query = ''
SELECT #Query = 'SELECT *
FROM (
SELECT ROW_NUMBER() OVER(ORDER BY ' + #SortingCol + ') AS rownumber,' +#SelectList +
' FROM ' + #FromList
IF rtrim(ltrim(#WhereClause)) <> ''
BEGIN
SELECT #Query = #Query + ' WHERE ' + #WhereClause
END
SELECT #Query = #Query + ' ) AS tbl
WHERE rownumber > ' + CONVERT(varchar(9), #lbound) +
' AND rownumber < ' + CONVERT(varchar(9), #ubound)
EXEC (#Query)
End

Resources