I have a Student table and Department table. Student Table contains Three columns
StudentId | DeptId | StudentName
Department Table contains
DeptId | DeptName
It may be the case that DeptTable sometimes doesnot exists. That is I am deploying script with two scenarios sometimes with department and sometimes without. In the case without department , departmentId will not be there in student table So when Department table exists I have to insert value of DeptId otherwise I have to write insert statement without departmentId
IF (EXISTS(
SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'Department'
AND column_name = 'DeptId'
))
DECLARE @DeptId UNIQUEIDENTIFIER;
SET @DeptId = Select DeptId From Department Where DeptName = 'Computer'
INSERT INTO Student ([DeptId], [StudentName])
VALUES (@DeptId, 'TBAG')
But as DeptId column sometimes not present I need to create dynamic Sql.
So I created Select statement
DECLARE @sqlCommand nvarchar(1000)
DECLARE @DeptName varchar(75)
declare @DeptId uniqueIdentifier
SET @DeptName = 'Computer'
SET @sqlCommand = 'SELECT @dept=DeptId FROM customers WHERE DeptName = @DeptName'
EXECUTE sp_executesql @sqlCommand, N'@DeptName varchar(50),@dept uniqueIdentifier OUTPUT', @DeptName = @DeptName, @dept=@DeptId OUTPUT
But how to write Insert statement I am not getting