--Way 1:-
DECLARE @Query NVARCHAR(4000)
,@TodayDate NVARCHAR(1000)
SET @Query = N'SELECT @TodayDate = GETDATE()'
EXEC SP_EXECUTESQL @Query, N'@TodayDate NVARCHAR(1000) OUTPUT', @TodayDate = @TodayDate OUTPUT
SELECT @TodayDate AS TodayDate
--Way 2:-
CREATE TABLE #FruitName(Id INT IDENTITY,Name VARCHAR(100))
INSERT INTO #FruitName(Name) VALUES('Apple')
INSERT INTO #FruitName(Name) VALUES('Mango')
INSERT INTO #FruitName(Name) VALUES('Banana')
INSERT INTO #FruitName(Name) VALUES('Pineapple')
DECLARE @Query NVARCHAR(4000)
,@Name NVARCHAR(1000)
,@Id NVARCHAR(1000)
SET @Id = '1'
SET @Query = N'SELECT @Name = Name FROM #FruitName WHERE Id = '+@Id+''
EXEC sp_executesql @Query, N'@Name NVARCHAR(1000) OUTPUT', @Name = @Name OUTPUT
SELECT @Name AS Name
--Way 3:- Using Placeholder
DECLARE @Query NVARCHAR(4000)
,@Name NVARCHAR(1000)
,@Id NVARCHAR(1000)
SET @Id = '1'
SET @Query = N'SELECT @Name = Name FROM #FruitName WHERE Id = @Id'
EXEC sp_executesql @Query, N'@Id NVARCHAR(1000), @Name NVARCHAR(100) OUTPUT', @ID = @ID, @Name = @Name OUTPUT
SELECT @Name AS Name
--Way 4:- Using Temp Table
DECLARE @Id NVARCHAR(1000)
SET @Id = '1'
CREATE TABLE #Name(Name VARCHAR(100))
INSERT INTO #Name EXEC('SELECT Name FROM #FruitName WHERE Id = '+@Id+'')
SELECT * FROM #Name
DROP TABLE #Name
--Way 5:- Using Table Variable
DECLARE @Id NVARCHAR(1000)
SET @Id = '1'
DECLARE @FruitName AS TABLE(Name VARCHAR(100))
INSERT INTO @FruitName EXEC('SELECT Name FROM #FruitName WHERE Id = '+@Id+'')
SELECT * FROM @FruitName
--Drop Temp Table
DROP TABLE #FruitName
No comments:
Post a Comment