my problem is While passing 2 parameters month and year of varchar datatype,i need to club two by '/' and i need to compare with a coloumn(month/year) and then have to show in SQL server. can any one please help me.. thanks in advance
Here is an example table I created :
Create table SampleTable (Id numeric(10,0) identity(1,1) primary key, MonthAndYear varchar(7));
Insert into SampleTable values('01/14');
Insert into SampleTable values('02/14');
And the stored procedure :
Create procedure compareMonthAndYear
#month varchar(2),
#year varchar(2)
AS
BEGIN
SET NOCOUNT ON;
Select * from SampleTable s
where s.MonthAndYear like (#month + '/' + #year)
END
Run the stored procedure like :
compareMonthAndYear '02','14'
Hope you could get an idea!
Related
I have a table that was created to show a client's areas in rows not columns. I created a pivot as a solution for this. I understand that there are other options like CASE statement and JOINS that might also work. The next step was to see if I can add it to a function or Stored Procedure. I was not able to find something to help me with functions or table functions that was easy to understand, or I am too stupid. I did create a SP, but I can't seem to use it within a SELECT statement as per some blogs I read. So, to all the experts out there what is the best practice to make sure I do this effectively.
DATA EXTRACTION BEFORE
DATA EXTRACTION WITH PIVOT
The above is the data I extracted from one client - I will have anything from 10K to 50K records if not more. Not sure if that is relevant?? But the issue is that I need to link it to the client table and address table and and....
Below is my pivot attempt and my SP attempt as well as my Table Function.
Then when I try to do a table function, I get this error as per >>> [![PIVOT TABLE FUNCTION](https://i.stack.imgur.com/WWDhq.png)](https://i.stack.imgur.com/WWDhq.png)
Also this error: Invalid use of a side-effecting operator 'EXECUTE STRING' within a function
If anyone can point me in the right direction or advise me what I need to look for to continue my google search, I would and will really, really appreciate it.
Thanks
> SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ======================================================
-- Author: Stefan Kleinhans
-- Create date: 02-11-2022
-- Description: Supplying client areas in single columns
-- ======================================================
CREATE FUNCTION [crm].[UDF_GetClientAreas_Gain] (#AreaGroup Varchar(10), #TenantId INT)
RETURNS #T TABLE
(
TenantID INT,
CustID INT,
Division Char(2),
Technical Char(3),
SubDivision Char(3),
MainArea Char(3),
SubArea Char(3)
)
AS
BEGIN
DECLARE #FieldList varchar(1000)
/****** Script for SelectTopNRows command from SSMS ******/
SELECT #FieldList = CONCAT('[',STRING_AGG([AreaType],'],['),']')
FROM (
SELECT DISTINCT [AreaType], GroupLevel
FROM [Xyro_ADF].[crm].[dimClientAreas]
WHERE AreaGroup = #AreaGroup
AND AreaType <> 'Division'
) a
DECLARE #Str varchar(max)
SET #Str = 'SELECT TenantID, CustID, Division, ' + #FieldList + ' FROM
(
SELECT TenantID, CustID, Division, AreaType, AreaName
FROM [Xyro_ADF].[crm].[dimClientAreas]
WHERE AreaGroup = ''' + #AreaGroup + '''
AND TenantID = ' + CONVERT(varchar,#TenantId) + '
) AS DataTbl
PIVOT
( MAX(AreaName) FOR AreaType IN (' + #FieldList + ')
) AS PVTbl'
--PRINT(#Str)
EXEC(#Str)
RETURN
END
USE [Xyro_ADF]
GO
/****** Object: StoredProcedure [dbo].[usp_ClientArea_Pivot] Script Date: 28/10/2022 07:19:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ====================================================================================
-- Author: Stefan Kleinhans
-- Create date: 28-Oct-2022
-- Description: A procedure that uses dynamic SQL for a PIVOT operation
-- ====================================================================================
CREATE PROCEDURE [dbo].[USP_ClientArea_Pivot]
(#TenantID INT,
#CustID INT)
AS
BEGIN
DECLARE
#Col VARCHAR(MAX),
#Str VARCHAR(MAX)
SET NOCOUNT ON
SET #Col = (SELECT STRING_AGG(AreaType, ', ') FROM (SELECT DISTINCT AreaType FROM [Xyro_ADF].[crm].[dimClientAreas] WHERE AreaType <> 'Division') AS x)
SET #Str =
'SELECT AreaGroup, Division, '+ #Col +'
FROM
(SELECT TenantId, CustId, AreaGroup, Division, AreaType, AreaName
FROM [Xyro_ADF].[crm].[dimClientAreas]) AS Source_Table
PIVOT
(MAX(AreaName) for AreaType IN ('+ #Col +')
)as Pivot_Table
WHERE TenantId = '+ CONVERT(VARCHAR,#TenantID) +'
AND CustId = '+ CONVERT(VARCHAR,#CustID) +' '
EXEC (#Str)
SET NOCOUNT OFF
END
GO
/* EXECUTE SP WITH #TenantId & #ClientId */
--EXEC [dbo].[usp_ClientArea_Pivot] 1,33395
I'm looking for something can help me to get the id of the ticket created at the first row.
I know i can simplify this by using different prepared query but I want not (try and see if it possible by this way and if it's not using the multiple queries way.
I know LAST_INSERT_ID() in mysql but I'm a little worried about inserting several lines at the same time....
During my research I also see someone directy SELECT the specified ID but it's a big cost of ressources.
I also see ##INSERTED and i didn't see a big difference between them, so i had the same problem...
The code :
CREATE PROCEDURE `Create_Ticket`(IN idU bigint(16),IN type VARCHAR(45),IN pseudo VARCHAR(45), IN lienacc VARCHAR(100), IN liengame VARCHAR(100), IN content VARCHAR(500))
BEGIN
INSERT INTO `dbOneT`.`Ticket` (`FaceitGame`,`Status`,`Ouverture` )
VALUES ( liengame , 0 , NOW());
INSERT INTO `dbOneT`.`Users_has_Ticket` (`Users_id`, `Ticket_id`)
VALUES ( idU, `Ticket`.`idTicket` );
INSERT INTO `dbOneT`.`Accuse` (`Pseudo`,`LienFaceit`)
VALUES (pseudo, lienacc);
INSERT INTO `dbOneT`.`Ticket_has_Accuse` (`Ticket_id_A`, `Accusé_id`)
VALUES (`Ticket`.`idTicket`, `Accuse`.`idAccuse`);
END
I'm running MariaDB 10.3.27
The "computer" is a raspberry pi 4B with 8go ram
On Raspberry Pi OS (A debian)
thanks for your help and have a nice day
Tom
CREATE PROCEDURE `Create_Ticket`(IN idU bigint(16),IN type VARCHAR(45),IN pseudo VARCHAR(45), IN lienacc VARCHAR(100), IN liengame VARCHAR(100), IN content VARCHAR(500))
BEGIN
-- declare variables for inserted PK AI values
DECLARE _idTicket INT;
DECLARE _idAccuse INT;
INSERT INTO `dbOneT`.`Ticket` (`FaceitGame`,`Status`,`Ouverture` )
VALUES ( liengame , 0 , NOW());
-- save assignerd AI value to the variable
SET _idTicket := LAST_INSERT_ID();
INSERT INTO `dbOneT`.`Users_has_Ticket` (`Users_id`, `Ticket_id`)
-- use saved value
VALUES ( idU, _idTicket );
INSERT INTO `dbOneT`.`Accuse` (`Pseudo`,`LienFaceit`)
VALUES (pseudo, lienacc);
-- save assignerd AI value to the variable
SET _idAccuse := LAST_INSERT_ID();
-- use saved values
INSERT INTO `dbOneT`.`Ticket_has_Accuse` (`Ticket_id_A`, `Accusé_id`)
VALUES (_idTicket, _idAccuse);
END
Summary: I am trying to add a Username to the db.username_table with a unique ID incremented by 1. However, I keep receiving an error 1111 related to my CASE statement. It should make the first User_ID 1, then all other new ones the max(user_id) +1. Any help would be greatly appreciated!
Background: This is for my first MySQL project - I have some experience with MS SQL that may be hindering me here. I googled many references and streamlined my code as much as possible, but the aggregate for the counter returns a 1111 error with an IF or with a CASE statement.
DELIMITER $$
CREATE PROCEDURE db.add_user
(
in new_username varchar(45)
)
begin
-- Set Counter ID
declare new_user_id int;
set new_user_id = if(max(db.username_table.User_ID) is null, 1, max(db.username_table.User_ID) + 1);
-- Add Username with Counter
insert into db.username_table (user_id, username)
values (new_user_id, new_username);
END$$
DELIMITER ;
Expected Result - Add a Username to the db.username_table with a unique ID incremented by 1.
Actual Result - Error 1111.
You are using the funtion MAX but not in SQL statements .. so the max of is used improperly . you need a select for retrive a MAX(db.username_table.User_ID.)
declare new_user_id int;
select case when
max(ifnull(db.username_table.User_ID,0)) = 0
then 1
else max(db.username_table.User_ID) + 1 end
INTO new_user_id
from your_table ;
but could you simply need an autoincrement column for User_id and avoid this SP
CREATE TABLE your_table (
User_ID int(11) NOT NULL AUTO_INCREMENT,
....
)
I'm trying to use tSQLt to test a stored procedure that returns JSON data. The database is running under SQL Server 2016. The stored procedure is as follows (simplified considerably):
CREATE PROCEDURE [SearchForThings]
#SearchText NVARCHAR(1000),
#MaximumRowsToReturn INT
AS
BEGIN
SELECT TOP(#MaximumRowsToReturn)
[Id],
[ItemName]
FROM
[BigTableOfThings] AS bt
WHERE
bt.[Tags] LIKE N'%' + #SearchText + N'%'
ORDER BY
bt.[ItemName]
FOR JSON AUTO, ROOT(N'Things');
END;
This can't be tested in the same way XML can - I've tried a test table, as below, which was suggested in this related answer here -
CREATE TABLE #JsonResult (JsonData NVARCHAR(MAX))
INSERT #JsonResult (JsonData)
EXEC [SearchForThings] 'cats',10
The above code produces this error:
The FOR JSON clause is not allowed in a INSERT statement.
I cannot alter the stored procedure under test. How can I capture the JSON result?
Without being able to modify the stored proc, your last ditch effort would be to use OPENROWSET. Here's how you would call it in your case:
INSERT INTO #JsonResult
SELECT *
FROM OPENROWSET('SQLNCLI', 'Server=[ServerNameGoesHere];Trusted_Connection=yes;','EXEC SearchForThings ''cats'',10')
If you get an error, you can use the following to enable ad hoc distributed queries:
sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO
I know this is two years on but I stumbled on this today when trying to solve a different tSQLt problem.
Your issue occurs because the column being returned from your stored procedure is not explicity named. If you provide a column name for the JSON data you can insert the data into a #temp table, e.g.:
create table BigTableOfThings (
Id int not null,
ItemName nvarchar(50) not null,
Tags nvarchar(50) not null
);
insert BigTableOfThings values
(1, 'Whiskers', 'Cool for Cats'),
(2, 'Barkley', 'Dogs Rule!');
GO
create procedure SearchForThings
#SearchText nvarchar(1000),
#MaximumRowsToReturn int
as
begin
select [JsonData] = (
select top(#MaximumRowsToReturn)
Id,
ItemName
from
BigTableOfThings as bt
where
bt.Tags like N'%' + #SearchText + N'%'
order by
bt.ItemName
for json auto, root(N'Things')
);
end
go
create table #JsonResult (JsonData nvarchar(max));
insert #JsonResult (JsonData)
exec SearchForThings 'cats',10;
select * from #JsonResult;
go
Which yields...
{"Things":[{"Id":1,"ItemName":"Whiskers"}]}
I have a variable table:
DECLARE #A_Table TABLE(ID INT, att1 VARCHAR(100), att2 nvarchar(200))
I want to make dynamic sql, so I insert into this table some data (all inside a loop):
WHILE (#i <= 100) BEGIN
SELECT #other_att = NAME FROM #other_Table where ID = #i;
SET #sql = 'INSERT ' + #A_Table+ '(ID,att1,att2) SELECT '+CAST(#i AS VARCHAR)+' , '''+ #other_att+''', SUM('+ #other_att') FROM '+ #EVEN_OTHER_Table;
EXEC (#sql);
END
sql every time would look like:
INSERT INTO #A_Table SELECT 1 , 'subject', SUM(subject)
INSERT INTO #A_Table SELECT 2 , 'age', SUM(age)
INSERT INTO #A_Table SELECT 3 , 'sex', SUM(sex)....
AND after executing this :
SO I will get:
#A_Table:
id att1 att2
1 subject 4.3
2 age 4.5
3 sex 4.1
but I get an error:
Msg 137, Level 16, State 1, Line 48
Must declare the scalar variable "#A_Table".
SO what is it the syntax to insert dynamically into a variable table?
Ok I have understood it.
You could use the INSERT ... EXEC syntax to insert the data returned by the dynamic SELECT. Of course, you would then need to remove the INSERT part from the dynamic statement.
WHILE (#i <= 100) BEGIN
SELECT #other_att = NAME FROM #other_Table where ID = #i;
SET #sql = 'SELECT '+CAST(#i AS VARCHAR)+' , ''' + #other_att+''', SUM('+ #other_att + ') FROM '+ #EVEN_OTHER_Table;
INSERT INTO #A_Table (ID,att1,att2)
EXEC (#sql);
END
You have a table variable, not a variable that contains the table name.
So you would need the following.
WHILE (#i <= 100) BEGIN
SELECT #other_att = NAME FROM #other_Table where ID = #i;
SET #sql = 'INSERT INTO #A_Table (ID,att1,att2) SELECT '+CAST(#i AS VARCHAR)+' , '''+ #other_att+''', SUM('+ #other_att') FROM #EVEN_OTHER_Table';
EXEC (#sql);
END
You would also need to declare the table variable as a statement inside the #sql variable, and execute your declare table and inserts together, or use a local/global temporary table.
With a local temporary table (stored in the tempdb) you could do something like this.
CREATE TABLE #testtbl (ID INT);
EXEC ('INSERT INTO #testtbl VALUES (1)');
SELECT * FROM #testtbl
DROP TABLE #testtbl
Some good info about temporary tables in BOL
http://msdn.microsoft.com/en-us/library/ms174979.aspx - quite far down the page
And the table type.
http://msdn.microsoft.com/en-us/library/ms175010.aspx
Your EXEC statement occurs in a different context and is therefore unaware of any variables created in your original context.
To create dynamic insert query it is really a task, I also struggle to find it ,finally I have tried in the following way and it's successfully working. Please find the code below.
CREATE PROCEDURE [dbo].[InsertTodaysData] (#tbl varchar(50),#Days int,
#MDate varchar(50), #EValue varchar(50), #Speed varchar(50),
#Totalreturn varchar(50),#Closingv varchar(50), #TotalReturnV varchar(50))
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #SQLQuery varchar(2000)
-- Insert statements for procedure here
set #SQLQuery = 'INSERT INTO '+#tbl+' (ID,MDate,EValue,Speed,TotalReturnRatio,ClosingValue,
TotalReturnValue) VALUES ('+#Days+','''+#MDate+''', '+#EValue+', '+#Speed+',
'+#Totalreturn+', '+#Closingv+', '+#TotalReturnV+')'
EXECUTE(#SQLQuery)
END
Hope this will help you..